Sie sind auf Seite 1von 34

JAVA FOR THE BEGINNERS

Now, Logic is a wonderful thing but it has, as the process of evolution


discovered, certain drawbacks. Anything that thinks logically can be
fooled by something else that thinks at least as logically as it does.

This page is not meant for someone trying to teach himself Java, or for a thorough
understanding of the contents and syntax of Java. If you want tutorials or books
that will enable you to learn Java by yourself check out the FAQs and Tutorials
Section, or the Java Books Section. This section is meant for the absolute beginner
to Java and programming. It gives a brief and basic understanding of some of the
basic concepts of Java, meant for the person whom is about to start a Java class
and has an extra hour, and doesn't want the whole class to be ahead of him, or for
the whole lecture to fly right over his head. Reading the following links will give
him a basic background to enable him to have a framework, that he can place in it
the bricks of Java knowledge to build with. Also, this is meant for the student
whom has gone to class, and was unable to follow, reading this will help him.

• What is computer programming?


• How to set up Java my computer? Setting up the class and classpath.
• Basic Java terminology: Variables, Strings, ints, interface, GUI, Keywords,
etc.
• What are Applications and Applets?
• What is Debugging, and how do I do it?
• What are control statements?
• What are arrays and data structures?
• What are Objects, Classes, Inheritance and Methods?
• Advanced topics: Exceptions, Multithreading, Networking and I/O
(input/output)
• What is the API and Javadoc?

Writing computer programs means writing instructions, that will make the
computer follow and run a program based on those instructions. To explain how
programming works, I will give a brief history. The basic instructions are
composed of a sequence of ons and offs, that the computer follows as it runs them
through the processor, turning switches on and off. The ons are coded (meaning
written in programming) with an 1, and the offs with a 0. Numbers and letters are
also represented by this; 0000=0, 0001=1, 0010=2, 0011=3, etc. In the beginning,
programs looked like "1010100100101111010101010101". Someone realized that
since the purpose of writing programs is in order to make life easier, why don't we
write a program that will take a kind of code that is easier to create, and the
program will translate it into computer code (1s and 0s). So, assembly language
was created, where the code then looked like "add $5, $7, $8 #comment", which
although not completely readable, it was a lot better than "010101". The program
that converted the assembly language into computer code was called the
assembler. Then someone decided, why don't we make a program that will
translate English-like words into assembly language, so we can write code in
English. Thus modern "third generation" code was created. Now the programmer
can write code like "x = 5 + 8;" or "String stupid = "You are not smart;". (The first
piece means that x will equal 5 + 8, and the second means that whenever the
program writes stupid it means the words in the quotes. However, that is not
important now, the important thing to realize is that programming is more
"Englished" and understandable than before".) Now, a compiler will translate the
new code into assembly language, to which an assembler will translate into
computer language, that the computer will execute into a series of ons and offs.
This new way enabled writing more complex code, as it was now more readable
and easy to program. Java is one of the newer languages that uses this third
generation code writing technic.

In short, writing code means writing a bunch of instructions. Each instruction is


relatively simple, yet because of the computer's speed, it is able to run millions of
instructions in a second. In order for a complex 3d game, like for example Diablo,
millions of little code lines are being executed per second, as each code line only
does very little. Your job as a programmer is to be able to not focus only on what
the end product looks like, but on how each little piece runs, and then being able to
write all of the little lines of code that enable the whole program to run. When you
learn how to program you learn how to break up the objective into different
chunks, and work only on that chunk at a time. This is in order to focus on what
you need to do right now, and that which you don't need to know is pushed off to
be done at a different time. For example, when you are writing code for a game,
when you are focusing on the good guy fighting, you ignore the rest of the game,
and only focus on getting the guy to swing the sword, etc. When you are writing
the code on how the good guy finds and picks up treasure, you write only the code
for that, ignoring, the code on how he fights. Then, you take a step back and put
the pieces together. Although this seems hard, it is one of the basic aspects that
you are taught when you write programs, and you become extremely used to it.
This is known as abstraction.
One writes code with a specific terminology for the language that he is
programming in. The different terminologies can be grouped into the few
categories of keywords, variables, operations and predefined classes (in Java).
(This is an oversimplification, as I am trying to make this easy to be understood
for beginners). Keywords are the words that have a specific meaning to the
compiler. For example, "if" tells the compiler that "if the condition is true then run
the next piece of code". Operations are symbols that give specific meaning. For
example, the operation of "+" can be used to add two numbers together. The
operation of "=" means that the operand (the thing using the operation) on the left
"gets" what is on the right. Variables are the values that you give to a word that
you make up. For example, in Java the keyword "int" means a number. If you
write "int sum = 8 + 7;" you are telling the compiler, I want a variable called sum
to get the value of 8 and 7 added together. From now on until you change it,
whenever you write "sum" in the program, the compiler reads it as "15". For
example if you were to write "if (sum==15)" means if that variable called sum
equals 15 (which for now it has not been changed) then run the next piece of code.
(for more see the terminology section.) Also, in Java you have already made
classes that will do a huge amount for you. All you have to do is bring them into
your code, and it will save you a huge amount of programming.

How to set up Java on my computer

The very first thing to do is install the Java Developer's Kit (jdk) onto your
computer. Sometimes if you buy a Java book it comes on a CD with the book.
However, usually you have to go to Sun's Java site, in order to download it. For
simplicity, you can go to Downloading compilers where it will explain to you how
and what kind of Java Developer's Kit to download. After you have downloaded
the jdk you will have to follow their simple installation instructions. There are two
ways to run a program. The basic way is to click on the start button on the bottom
of the Windows desktop, click "run" and type in "CMD". If you did not set the
path (see next paragraph how) you will then have to find the bin directory. In my
computer I typed "cd.." until I reached C:\>, I found my Java directory (on my
computer it was j2sdk1.4.1, but may be different on yours), and then the bin
directory. If you have set the path, then you can run Java in any folder that you
want. I then typed "edit Hello.java". "Edit" opens a simple editor (writing
program), and the name of my program is called "Hello.java". Every Java class
has the .java extension. I wrote up a simple code that displays to the screen
"welcome to programming". I saved, exited, and then typed "javac Hello.java".
Javac stands for Java compiler, and the computer then compiles (meaning converts
from what you wrote into a language that the computer can understand) my
programs. If I were to look at my folder, I would find a new class called
Hello.class. When I compiled my "Hello.java", the compiler created a
"Hello.class", which is in computer understood language. If you try to read it, it
will look like garbage, because it is in a language that only the computer can read.
I then type "java Hello", which tells the computer to run the class called "Hello".
(Note in Java capitalization makes a difference. If your class is called Hello, and
you type java hello, it will not work.) Once you are familiar with programming, a
better choice would be write your program using an editor or an IDE, which
makes writing code easier. Go to Downloading an editor or an IDE to figure out
which one you want, and how to get one.

Setting the path. The commands of "javac" and "java" (amongst others), are not
system commands, they are Java commands. Meaning, that if you are in the Java
bin directory, then the computer understands what these commands mean. If you
are out of that directory, then the computer doesn't understand what these
commands mean. In short, you do not need to set the path, but if you don't all of
your programs will have to be in the bin directory. If you would want to create a
file in the C directory, and call it javawork, and keep all of your code in that
folder, then you need to set the path. How? The following is taken from Deitel's
Java How To Program

Update the PATH variable in Windows

Next, you will set your system's PATH variable to conveniently run
the Java 2 SDK executables (javac.exe, java.exe, javadoc.exe, etc.)
from any directory without having to type the full path of the
command. If you don't set the PATH variable, you need to specify
the full path to the executable every time you run it, such as:

C:> \j2sdk1.4.1\bin\javac MyClass.java

While you do not need to set your system's PATH variable to run
Java, other software you will install later expects that your PATH
variable will already have been set.

It's useful to set the PATH permanently so it will persist after


rebooting.

How do I set the PATH permanently?

To set the PATH permanently, add the full path of the


j2sdk1.4.1\bin directory to the PATH variable. Typically this full
path looks something like C:\j2sdk1.4.1\bin. Set the PATH as
follows, depending on the version of Windows you are using:

Windows NT, Windows 2000, and Windows XP - To set the


PATH permanently:

a. Choose Start, Settings, Control Panel, and double-click


System. On Windows NT, select the Environment tab; on
Windows 2000 select the Advanced tab and then
Environment Variables. Look for "Path" in the User Variables
and System Variables. If you're not sure where to add the
path, add it to the right end of the "Path" in the User
Variables. A typical value for PATH is:

C:\j2sdk1.4.1\bin

Capitalization doesn't matter. Click "Set", "OK" or "Apply".

The PATH can be a series of directories separated by semi-


colons (;). Microsoft Windows looks for programs in the
PATH directories in order, from left to right. You should only
have one <b>bin directory for a Java SDK in the path at a
time (those following the first are ignored), so if one is
already present, you can update it to j2sdk1.4.1.

b. The new path takes effect in each new Command


Prompt window you open after setting the PATH variable.

Windows 98, Windows 95 - To set the PATH permanently, open


the AUTOEXEC.BAT file and add or change the PATH statement
as follows:

a. Start the system editor. Choose "Start", "Run" and


enter sysedit, then click OK. The system editor starts up with
several windows showing. Go to the window that is
displaying AUTOEXEC.BAT

b. Look for the PATH statement. (If you don't have one,
add one.) If you're not sure where to add the path, add it to the
right end of the PATH. For example, in the following PATH
statement, we have added the bin directory at the right end:

PATH
C:\WINDOWS;C:\WINDOWS\COMMAND;C:\J2SDK1.4.1\BIN
Capitalization doesn't matter. The PATH can be a series of
directories separated by semi-colons (;). Microsoft Windows
searches for programs in the PATH directories in order, from
left to right. You should only have one bin directory for a
Java SDK in the path at a time (those following the first are
ignored), so if one is already present, you can update it to
j2sdk1.4.1.

c. To make the path take effect in the current Command


Prompt window, execute the following:

C:> c:\autoexec.bat

To find out the current value of your PATH, to see if it took


effect, at the command prompt, type:

C:> path

Windows ME - To set the PATH permanently:

From the start menu, choose Programs --> Accessories --> System
Tools --> System Information. This brings up a window titled
"Microsoft Help and Support". From here, choose Tools --> System
Configuration Utility. Click the Environment tab, select PATH, and
click Edit. Now add the SDK to your path as described in step B
above. After you've added the location of the SDK to your PATH,
save the changes and reboot your machine when prompted.

Setting up the classpath. This is something that you will not need to do right away.
However, when you start programming using packages besides for the packages
which are part of Java's standard API (meaning the packages that come
automatically with the jdk), then you will need to set the classpath. If you do not
set the classpath, then when you try compiling a class from package "libraries" (a
random name that I made up for a package name), that you either created or
installed from a different Java developing program, the compiler will not know
where to find this package. Therefore you will have to set your classpath to find
these packages, even if these are packages that you created. You can read about
how to set the classpath from sun by going to Java's tool Documentation 1.4 or
Java's tool Documentation 1.5 and click on the "setting the classpath" link for your
operating system.
Basic Java terminology

The purpose of this page is to help the beginner with the basic Java terminology.
Advanced programmers and teachers often use words that are very common in
Java and computers without explaining them because they are so accustomed to
using them. Therefore, the beginner is often unable to understand what is being
taught, because he is lacking in the basic vocabulary. The terminology below is
meant to be easily understood, and is therefore not given a technical definition.

• processor: The processor is inside the brain of the computer, and it is its
job to read, or process, the instructions. It takes each instruction (after it has
been broken down into basic computer language by the compiler) and runs
it, turning on and off switches, causing the program to execute.
• CPU: The CPU or Central Processing Unit, is the brain of the computer. It
holds inside it the processor, the Arithmetic Logical Unit (ALU: the
computer's math machine), and controls and tells the rest of the computer
what to do.
• code: Code just means the instructions that the programmer writes. The
code of a program means the part that the programmer wrote up, and will
give to the computer to run.
• compiler The compiler "translates" the code that you have written in the
language that you understand (like Java) into a language that the computer
understands, either assembly language, or pure computer language (ones
and zeros).
• keywords: Keywords are words that have a very specific meaning to the
compiler. Whenever the compiler sees one, it knows what it is, and
translates it as such. For example, the word"int" means a number.
Whenever in the program the programmer writes "int", it has only that
meaning, a number. The programmer can never use it for something else.
Another example is the word "if". If means try to see if what I am saying is
true. If it is then do the next line, if not not. The word if can only mean that,
and can never change. There are approximately 30 keywords.
• control statements: Whenever the computer runs a Java program, it goes
straight from the first line of code to the last. However, lets say you only
want to run some code on condition. For example, you are writing an
adventure game, and your player is hit, do you want him to die, or not.
Well, it depends, how many "hits" is he allowed to have before he dies. So
you want a control statement that says "if he is down to his last hit, then run
the dying code, else subtract the number of hits that he is allowed, and
continue". The if else is one kind of control statement, and it changes
control to read from a different line of code, instead of the next. For more
see the Control statements section.
• variables Variables are words in your code, that have different meanings
based on different times in the program. Why would I want that? The
reason is, that that which makes a computer so powerful, is the ability to be
given a set of instructions, and act differently based on the circumstances.
For example, in the adventure game, your player has the ability to be hit 5
times before he dies. That number is going to change, as he runs through
the game. Sometimes when he gets to the tower (for example) he will have
4 "hits" remaining, sometimes he will be down to his last one, and when the
bad guy comes and hits him he will die. How is the computer able to keep
track and know this? With variables. There will be one variable that is
called "life", and you will start it off with 5. Every time that the player gets
hit, you will tell life to subtract from itself one. You will also check, if life
equals zero, then run the code to die. Since "life" is a variable and not a
keyword, you will create this word. I called it life, but you can call it
whatever you like. Also, when you go online, the computer asks you to tell
them your name. You type in "Shlomo" (assuming that that is your name).
Then for the rest of the time that you are on that site they always call you
Shlomo. You go onto a new page, and they say "Shlomo, what do you want
to buy?". They don't have a hundred premade web pages for each name.
Instead, they collect your name into a variable, let's call firstName, and
have one web page that says "print out 'firstName, what do you want to
buy'".
• operations and operands: Operations are symbols that have a specific
meaning. Operands are the words that use the operations. For example the
line " salary + bonus " means take the two operands of salary and bonus,
and use the operation of "+" to add them. In Java the operation of "+"
means to add, the operation of "=" means to get, and the operation of "=="
means equal. "int payment = salary + bonus " means create a number
variable called "payment" and let it get the variable of salary added to the
variable of bonus.
• int : in Java a number is represented by the word int. However, this is only
one representation. For a complicated number like 4.5, you will need a
different representation, like "double" or "float". The word "int" is a
keyword that means number. If you write "int payment" you are saying that
you are making a variable called payment that is a number. If you write "int
payment = 5" you are saying that you are making a variable called payment
that is a number and giving it the value of 5.
• String : A string is a variable that holds a word, or a few words, or a
mixture of characters, that do not mean anything besides for a quote.
Meaning: when I go online and they ask me for my name, I tell them
"Shlomo". They save that quote of "Shlomo" in a String variable. The
actual word "Shlomo" doesn't mean anything to the compiler. However,
whenever the program wants to call my name it says "print out that String
that we called firstName" and whatever is in that String is printed. For
example, if I were to write a piece of code "String message = "How are you
today?", I would be telling the computer that there is a variable called
message, and whenever I refer to that variable, I am referring to the String
of "How are you today?".
• Primitive : Almost everything in Java is an Object or Class, meaning that it
has inside it operations, behaviors and methods (meaning stuff). (See the
Object and Class section). Primitives are the exception. A primitive is only
what it is, and nothing more, it can not do anything but hold that one piece
of information that it is supposed to hold. For example, an int is a primitive.
It can only hold a number. A String is an Object, it can change itself.
Meaning, I can tell the String change yourself to be capitalized, and the
String of "hello" will change into "HELLO". A primitive can not do
anything besides hold itself.
• Debugging : debugging means finding the errors and fixing them. See the
debugging and fixing errors section.
• Objects, classes, class interfaces, methods, argument lists, parameters,
inheritance : check out the section on Object and Class.
• interfaces, user interfaces, and GUI : An interface simply means the way
that two entities communicate with each other. For example, if two people
write two separate programs that interact with each other, they
communicate with each other through an interface. If you write a program
that works on a real system, like an ATM, then in order to communicate
with the money dispenser, you will need an interface in between. An
interface allows the ability to say I don't know how you do what you are
doing, all I need is a common way to communicate and get the information
that you are giving me that I need to use, and give you only what you need
to use. (In Java there is a special thing called an interface, check out the
above note). A user interface is the way that a user interacts with a
machine. The user doesn't need to know how the machine works, or what is
going on inside, it just needs to be able to interact with it. The command
console below is a user interface. A GUI or Graphical User Interface is an
user interface, that talks to the user using graphics. For example, Windows
is a GUI. Instead of typing in the word "exit", "OK', or whatever you will
need to type, in a GUI you can press a button, use a scrollbar, etc.

A User Interface
The ability to talk to the computer. You need a new folder you type md, you
need the directory you type dir, etc.
A Graphical User Interface (GUI)
The ability to talk to the computer with graphics. You need a new folder you
right click, you need the directory you click the folder, etc.

What are Applications and Applets


Applications, in short, are computer programs that you write that run on your
computer. You start from scratch, and you write the whole program; you have full
control. Applications start by you typing onto the screen java NameOfClass. The
Java software on your computer looks for the class that has the same name (in this
case NameOfClass), looks to see if it has a main method. If it does it starts from
the main method, and continues until either the program finishes, or is terminated
by the user (i.e., by pressing control C).

Applets on the other hand are programs that you write, and put inside your web
page. When someone opens up your web page, he automatically downloads any
applet that you have on your web page, just like an image. But by an applet, you
can't always control how much of the screen the applet takes up. The applet is
shown with the web page on the browser. Let's say that the user has an applet that
is running on the browser, and he opens up a different window over your applet.
Your applet is going to have to know how to stop in middle of what it is doing,
and restart when the user goes back to your applet. Let's say the user resizes the
browser window, then your applet is going to have to know how to redraw itself.
That is a lot of work. The good news is that you do not have to do the work. When
you extend the Applet class (for now all that means is you write extends applet
after the name of the class), the browser does most of the work for you. The
browser supplies the "main" method, and around 200 methods that deal with the
window resizing, starting, stopping, etc. The browser is like a container that has its
own Java machine, and all that it needs is for you to fill in mainly two spots; what
do you want the applet to do when it starts and downloads the applet for the first
time, and what do you want for the applet to do when it needs to redraw itself
every time. For example, let's say that your applet comes with an image picture.
You want to tell the browser to download the image only once, and save it
temporarily, while the user is on your site. However, you want the browser to
redraw the picture every time something blocks it. Therefore, there are two spots
available, one where you tell it that when the user starts the applet the first time
download the picture, and the second for when you want the applet to redraw the
picture. If you told it to download the picture every time it needed to be redrawn
your applet would take forever, and if you told it to draw the picture only once
then if the user opened another window on top of it and takes it off, your picture
would not be redrawn. Therefore there are two main spots to fill, and the browser
does the rest of the work. Because the browser runs its own Java software (which
has to be this way, because the user might not have any of its own Java software
elsewhere), you have to follow the rules of the browser that it is running on. Some
browsers, especially the old ones, are unable to run Swing (advanced graphics),
and therefore if you care you would choose to use only the simple graphics that all
browsers use. See the Downloading Browsers section. Another difference is that
for security reasons applets are sometimes restricted in creating it's own network
connections, looking into your files, etc.

Debugging and fixing errors

Debugging means finding what the errors in your program are, and fixing them.
This is something that at times are very hard, but becomes a lot easier with
experience. There are two reasons why your program may not work. One is called
a syntax error. A syntax error means that you did not follow the syntax, or rules, of
the Java language. You forgot the semicolon, you mention a word that does not
exist (not a keyword, class, or a predefined variable), or you forgot to call a
variable properly, etc. These are all errors that can be checked by the computer.
When you compile, the compiler checks each line of code, did you follow the rules
or not. If it sees that you did not follow the rules, then it will not finish compiling,
and it prints out an error. The compiler is saying, "I can not compile this because
you are not following the rules, and I can't automatically fix it for you, because I
do not necessarily know what you really want". When you get a compiler error, it
usually looks like this. Notice a few things. The first line tells you where the error
is, what class the error is in, the line number of the error, and what the error is. In
my example cannot resolve symbol, meaning that the I do not understand what the
word means, it is not a keyword, a class, or a variable that is predefined. '('
expected meaning that I had just started a method, and after each method name
comes an '(', and I don't have one. The next lines explain it more, by telling me
which symbol is not resolved (in my error), exactly which class had the error (if
one class called or is part of another class), and points with an arrow '^' to the
exact problem. Notice a second thing. In my code I created two errors. I put a
space in the word private (a keyword) and I erased the "()" that was supposed to
go after the method. However, the compiler found seven errors, why is that? The
reason is because the first error caused that the compiler doesn't understand the
first line. In the first line I am creating a variable called noise, telling the compiler
that this is a kind of AudioClip, and telling it that it is private (a keyword that
means that not everyone can use it- don't worry about it now). Whenever the
compiler sees the word noise, it knows that it is a kind of audioclip. Now that I
"accidently" put a space in the word "private", the compiler doesn't know what
that line means (the words pri and vate don't mean anything to the compiler). So
the compiler doesn't assign the word noise to an audioclip, and it doesn't know
what the word noise means either. When you compile, a lot of times the compiler
gives you errors that shouldn't be there. You look at the error, and look, and it
seems that that line of code is exactly the way that it should be. The reason is
because just like in my case, the error happened many lines earlier. You should
first fix the errors that you understand, and then go through the list, fixing each
one that you see. You'll be surprised, sometimes you will fix a small error (like
you forgot the close brace) and twenty errors will disappear. What if you can only
see a few errors at a time? If you are using the "CMD" (you clicked start, then run
and typed cmd) in Windows XP, then you can right click the blue bar on top of the
window, and change the properties to have a larger window so you can see more
errors. If you are using an older version of Windows, then some allow you to
change the properties, and some don't. What you can do is use an editor, like
textpad that when it compiles it puts all of the errors on one of its own pages with
a scrollbar.

The second kind of error is a logic error. This means that the code compiles and
you have not broken any Java language rules. However, there is an error when you
run the program. These kinds of errors are a lot harder to fix, because you don't
necessarily know what causes the error. There are two kinds of logic errors. One
that when you run the program the program gets stuck and crashes. The other, is
where the program doesn't crash, but gives you the wrong results. In the second
case, the best thing to do is hide it, and hope that no one else discovers the mistake
(just kidding). In the first case, the screen will tell you which line caused the crash.
(In an applet, the program won't crash, but will continue running with messed up
results). This can sometimes be tricky, because the line that caused the problem
might be elsewhere, and it caused a different line to show up. Also when it shows
you the error, it shows a list of the chain reaction. Start at the top, because usually
that is what caused the error. For example, if you are working with graphics, and
you click the OK button, and now your program runs some complicated logic and
crashes, the error will give the chain reaction, all the way to the button being
pressed.

If you are stuck with an error that you can't resolve, then there are a few options.
The best one is to ask a friend. Sometimes something that is impossible to the
programmer is obvious to an outsider. Another option is to use an IDE which will
tell you what your error is, and might even be right. The most practical and used
technique is one known as printlns. You place a bunch of printlns
(System.out.println("what you want to be printed");) at various places in the
program. You tell it to print out information that you think should be according to
your understanding one way, and see if it actually prints it out the way that you
think it should. For example, let's say that you have created a complex math
program. However, you test it out, and the answer kept in the number variable of
finalAnswer is wrong. So you go through your code, and you cant figure out what
went wrong. So you write out a bunch of printlns, all with the variable
finalAnswer. In line 10 you tell the program to print out finalAnswer, in line 20,
etc., Lets say in your mind you worked out that in
line 10 -finalAnswer should equal 24,
line 20 -finalAnswer should equal 24,
line 30 -finalAnswer should equal 46,
line 40 -finalAnswer should equal 698,
line 50 -finalAnswer should equal 78.
However, because of the println's you notice that on
line 10 -finalAnswer is 24,
line 20 -finalAnswer is 24,
line 30 -finalAnswer is 55,
line 40 -finalAnswer is 454,
line 50 -finalAnswer is 26,
then you realize that the error is between line 20 and 30.

There are two main ways not to produce errors, and to promote that if an error is
caused it is easy to fix. The first is to read the code. Read it in real English, and
you will notice a lot of bugs. Meaning if you have a line of code that is written as
if(sum < sale) sale++; read it out loud as "If the sum is less than the sale, then add
one to the sale". When you read it out loud you might notice that you really need
the sum to be greater than, something that you didn't notice when it was in code.
The second way is to break up the problem into different working chunks, and
compile and run them separately. Imagine if your program was 1000 lines of code,
and you wrote it all at once, and compiled it. You might have 52 errors. 20 of them
might be because of one stupid error on top, like you forgot a '{'. When you see
that you have 52 errors you might give up and throw in the towel. However, if you
write one chunk of code at 50 lines each, it will become much easier. Also, again
for example, the first half of your code was meant to come up with a specific
number, and the second half was meant to do some computation. You can put in
middle of the code a number for the first half, run it, and when that works, work
on the first half. That way, if there is an error, you will only have to work on one
half of the code at a time.

As I wrote at the top, this is something that is harder in the beginning, but becomes
much easier when you get used to it. Good Luck.

What are control statements?

Whenever the computer runs a Java program, it goes straight from the first line of
code to the last. Control statements allow you to change the computer's control
from automatically reading the next line of code to reading a different one. Lets
say you only want to run some code on condition. For example, let's say that you
are making a program for a bank. If someone wants to see his records, and gives
his password, you don't always want to let him see the records. First, you need to
see if his password is correct. You then create a control statement saying "if" the
password is correct, then run the code to let him see the records. "else" run the
code for people who enter the wrong password. You can even put one control
statement inside another. In our example, the banking system has to worry about
people trying to get someone else's records. So, as the programmer, you give the
user three shots. If he misses them, then the records are locked for a day. You can
have code with control statements that look like this (not real code, only meant to
help you understand. also, Java doesn't have go back to earlier lines- again just
trying to focus on the control part.)

1. set variable counter to 0;


2. show screen asking for password;
3. if password is correct, run the code that let's him see the records;
4. else add one to the counter;
5. if counter does not equal three, then go back to line two and reshow the screen
6. else (meaning that this is the third time that he's messed up) then lock the
records and show screen "goodbye"

If you look at this psuedocode (code that is more understandable to a person, but
the computer can not understand it) you will see that one if else, is placed inside
the next if else. The way you read the control is like this. If the password is correct
then skip lines 4-6 that deal with incorrect passwords only. Else, (if the password
is incorrect) skip the end of line three and read line 4. Then if we have not hit the
third time go back, and never run line 6. However, if this is the third time, then
don't run the end of line 5, but run line 6.

Control Statements in Java are very simple. In some languages they have complex
control statements, that do a lot. However, Java offers only simple control
statements. If you need a complex control statement, you can build it with a few
simple ones. This makes control statements a lot easier to work with. Although
Java has a few different kinds, I will illustrate one more common one. The loop. A
loop is where you follow the same code over and over again, until some condition
stops it. For example, what if you were writing a program that spell checks each
word. You don't know how many words there will be, as every document will be
different. So you create a while loop and tell it, while there are more words, keep
on giving me the next word, I'll run the code to check if it is spelled correctly.
Then I'll start the loop again saying if there are more words give them to me. As
long as there is one more, the code will start from the beginning of the loop every
time.
1. while there are more words left to be checked
2. give me the next word
3. let me run some code to see if it is spelled correctly
4. check, if there are more words go back to line 1, else continue.

in short this is what a while loop looks like

1. while (some condition is true)


2. {
3. run this code again and again
4. }

What are Arrays and Data Structures?

You go to Ebay or an online store, and you buy a book, a computer, and a shirt.
How is the computer able to write a pointer and refer to that which you bought. It
didn't know what you were planning to buy. There aren't hundreds of programmers
hired by ebay to quickly write up a code for each user, writing "create a variable
for shirt, etc.". It must be that it has the ability to create a reference (pointer) to
each individual object. How? Besides the fact, how is it able to store your records.
Ebay has hundreds of people on record, and millions of pieces of merchandise.
How is it able to point to them all, and use each one individually?

Let's say that you have a hundred students in the class you are teaching. You have
a piece of code (method) that will calculate their grades for you. Are you going to
have to write the same code for each student
calculate grades for san
calculate grades for sue
calculate grades for sub
etc.
That's ridiculous.

The answer to both of these questions are data structures. Data structures loosely
defined are lists, and containers that store similar things. For example, you can
have a data structure that stores all of the students of your class. Whenever you
want to treat the whole class as one, you make use of this "list". Also, every thing
that you buy goes in a list, and therefore, ebay only needs to make one object for
you. A list. Then, whenever you buy something they add it to your list.

There are three ways to create a data structure, and get this list. The first way is
known as an array. An array is a built-in data structure, that comes automatically
with Java. It is the easiest to use, and the best kind if you want to pick out one
individual thing out of the list. An array can be made of anything. It can be made
of primitives (simple things in Java that are not an object. They can only do one
thing. Like an int, is a number, it can do nothing else), specific objects (like in my
example, you can make an array of students), generic objects (you can make an
array of objects, and store different objects in each one), or even of other arrays.
You can refer to the list, or to a specific person in the list. For example, lets say
that you have an array of students called AllOfMyStudents. If you want to refer
and use the whole array, you refer to it as AllOfMyStudents. (An array is written
also as AllOfMyStudents[]). But, if you want to refer to San, and San is the 10th
student in your array, then the word AllOfMyStudents[10] is referring to San.
(Actually Arrays start counting with number zero, so in reality
AllOfMyStudents[9] would be San). In my example where you want to calculate
the grades for all of your students in your class, and if all of your students are in an
array, you can do it using a Loop (see Control Statements ), and it will be easier,
and only take a few lines. This is what the pseudo code looks like.

1. start the loop to continue again and again until the condition stops
2. create a counter, start the counter at zero, and call the counter studentNumber
3. while there are more students keep on doing this, when there are no more
students continue after loop
4. take the student[] (remember, that the arrayName with braces refer to the
whole array
5. take the student[studentNumber] (remember, that the arrayName with a
number in the braces refer to an individual student, and here studentNumber is a
number variable, that keeps on going up by one)
6. do whatever code you need to do to calculate the grade of
student[studentNumber]
7. add one to the variable of studentNumber.

Notice, that it makes no difference if you have 10 students, or ten thousand


students, if they are all in an array this piece of code will run the same way.

Even though arrays are fast and easy to access and use, there's one big problem.
Once you create the array, it is technically impossible to add to the number, or
insert something in the middle. Therefore, there are two other kinds of data
structure solutions. One involves creating your own kind of data structure
(remember, an array is built into the Java language). This is an advanced topic,
that has college classes, and many different books just on it, but in short, think
about a chain. A chain is one object that is made up of many different links. Each
link is a thing by itself, and it also "points" to the next link. The same is true with a
linked list. You create the list, and if you want to go through the list, you just run
from one link to the next. There are many different kinds, and the "links" can hold
whatever information you want, depending on the way that you created it.
Meaning, you can make a linked list of students, or of numbers, since you write
the code of how it works.

The third way involves using a premade list from the Java library. As Java holds
many premade classes, some of their premade classes are premade lists, that you
can just bring in and use (see the Java API Library section). These are very easy to
use, but since they are made by someone else, you have to use them with the rules
that they come with.

What are Objects, Classes, and Methods, and what does Object Orientation
mean?

Java is an Object Oriented language, and understanding Object Orientation


(OO) is the backbone to understanding Java.

For many years, the advanced computer languages, amongst them C, were written
with a structured approach, and were known as structured languages. Structured
languages would group up a bunch of actions, and tie them together into a
function. Then, whenever they needed a certain action to be used, they would call
on that function to do it for them. The reason for using this approach, was in order
to help shorten the amount of code. Lets look for example at the action game
Prince of Persia. (Games are easiest to illustrate with, as you can see and explain
exactly what is happening. I picked this game because it is relatively simple,
although if you were to use a more complex game like Diablo or Alice, then you
would see the need for Object Orientation even more.) There are hundreds of
soldiers that the prince has to fight with, and many of the soldiers do exactly the
same thing. Imagine writing the same code for each soldier. That's no problem,
you say, I'll just cut and paste the code one hundred times, using "control C" and
"control V". Yes it is a problem. Suppose you finish writing the code for the game,
and your boss tells you that you have to change one detail in the soldiers. You're
going to have to find each soldier in the code, and change it. Of course you're
going to end up missing one, and your program is not going to work well. Suppose
he tells you to change all of the green soldiers. You're really going to be messed
up. This is true if you find an error, or for some other reason need to restructure
the whole game. The maintenance will become a nightmare. Imagine if this
wouldn't be a game, but a major online store or banking system. Also, imagine
how much memory the code for hundreds of soldiers would be. Therefore, the
programming language creators started structured language, where everything is a
function of actions. Therefore, in your Prince of Persia code, you only need to
write the actions of swinging the sword, jumping, attacking the prince, etc. once,
tie each action in a function and for each soldier call the same function. When the
prince reaches the second floor (for example), you will write the code for a soldier
to come, and call each function that the soldier needs. That would save you a lot of
coding.
Wait a second, you say, you can't do that. Not every soldier attacks in exactly the
same way. The yellow soldiers are fast at blocking, the tall guard in the seventh
level waits for you to make the first move, etc. If you write the same code for each
one, then all of the soldiers would be the same, and if you write complete different
code, then your stuck with your old problem of maintenance. After all, there's
usually only one small difference between one soldier and the next. No problem,
said the structured programming people, we can fix that. We will have one
function use most of the code of a different function. For example the prince
reaches the second floor, and there's a blue soldier. You write all of the action for
the blue, to attack, etc. The code to attack take up lines 150-200. You reach the
third floor (line 250), and there's another blue soldier. You tell this second blue
soldier to just borrow all of the code of the first soldier. You write in your code,
goto line 150, continue till line 200, and then come back here to line 260, instead
of continuing at line 201. You reach the fourth floor, and there's a yellow soldier.
You write in your code goto line 150, but since the yellow soldiers are better
blockers, only use lines 150-180, and when you get to line 180 come back to our
code. And even when the prince reaches more different soldiers, he can borrow
some of the functions of one soldier, and some of the next. That way everything
works out well. The basic function code is never repeated, while we can still be
flexible.

However, people noticed that there were two major problems. The first problem
was that using a structured language caused many bugs to occur, and made it
harder to fix. For example, lets say the green soldier borrowed some code from the
yellow soldier on line 270, and some code from the red soldier on line 400, and
adds some of its own. However, when the prince goes to fight the green soldier,
the green soldier doesn't fight back. Why? You read and reread the added code,
and it seems fine. Then you have to figure out, maybe when I went back and had a
goto earlier line, there was an error on the earlier line. But, why would it work
there and not work here? Hence, you would have a hard time finding where the
cause of the error came from. Also, let's say you decide to take out the red soldier
on line 400. Then without you realizing it, the code for the green soldier will not
work. The code will say, use a function from the red soldier at line 400, and there
is no red soldier at line 400. You'll have a pointer that is now pointing to
something that isn't there anymore. However, the main problem was that writing
actions and grouping them into functions does not mimic real life, and if you want
to write real lifelike games, then this is a must. In the game, you wrote the code as
a series of actions, where one action causes the next action. You filled the action
with data as necessary. Think of the Prince of Persia game as we described it until
now. When the prince, reaches the second floor, then the soldier walks, then the
soldier strikes, etc. You fill in the data of the soldier (what he looks like) just as
the side, and the main objective in the code is which action to do next. Life is not a
series of actions. When we bump into our friend San, it's not like San never
existed, and now he comes into play as a series of actions. San was always there as
a person, that also does certain actions. That bothered the programming people,
because if you want to write really complicated games, then you can't just have
groups of actions. You would have to have everything as objects, where you create
objects and use them, and each object will contain the actions that are necessary
inside the object. Hence Object Orientation was born. (I don't think that it was the
need for having more realistic computer games that drove for the creation of
Object Orientation, but lets face it, that is what really counts.)

Object orientation means that everything in the program is an object, mimicking


real life. In reality by a car, for example, there doesn't exist a function to drive, and
whenever any car needs to it "borrows" and uses that function. Rather, there are
many objects of cars, and each one has its own individual function to drive. An
object like a car is composed of methods, like driving, braking, opening and
locking a door, yelling at you when your seatbelt's off, etc, and data like the color,
make, model, etc. When you mimic this in a computer object, you also, create
methods and data. The data of an object is called fields or variables, and are
usually lower cased. The methods ( seen in the code as methodName()) contain
actions, like openDoor(), drive(), and inside each method are instructions on how
to do that. Also, one method may divide itself into smaller methods, and call each
method one after another. For example, method openDoor() might be made up of
and call smaller methods like unlockDoor(), pushDoorOpen(), moveSeatBelt(),
checkIfNightTime(), and then a turnLightsOn(), if it is night time. This helps you
write the code, by breaking up everything into smaller methods. If you are writing
the code for a car, and you need the car to open its door, you can write the words
openDoor(), and fill in how to do it later. Whenever you need the door to open, all
it takes is one method call, and you can call it whenever and wherever you want.
In the Prince of Persia game, you can have for the prince a method called jump(),
swingSword(), and walkForward(). Method walkForward(), will check what is in
front of the Prince. If there is a plank, then it will call method walk(), if there is
nothing it will call method fall(), and if there is a wall it will call method
wallAhead(). This makes it very easy to break up a large problem into smaller bits.
When you put all of the pieces together you're able to ignore the details of the
methods on how they work, and when you work on each method's details, you can
hide the big picture. This is necessary, as some games and programs are extremely
complicated, and it is impossible to see the big picture and all of the details at the
same time. Another example of this in the Prince of Persia game is the object
called soldier. In that soldier class you will put methods and data. Some of the
methods are attackPrince(), jump(), wasHit(), die(), etc, and some of the data will
be color, amount of time that he can be hit, etc. This data that we will call
canBeHit will be a int, or number, variable. When the soldier starts fighting, the
variable data canBeHit may start out as 5. In that case, when you start the code for
that soldier, you might tell the main program, see how many hits he has, and put
triangles for each hit that he can receive. Every time the soldier is hit by the
prince, the soldier's method of wasHit() is called. This method will start by calling
a smaller method of showHit() that will show on the screen the soldier being hit.
Then it will subtract the hit variable by one. Then it will check if canBeHit equals
zero. If it does it will call the method die(), if it doesn't it will call the method
weakened(), which it will be that method's job to tell the main program to lessen
one of the soldier's triangles. This is just an example, as I am trying to show how
one method uses the other methods and data.

There are two terms that seem confusing, and need to be clarified before I explain
more: classes and objects. Up until now I have been using these two terms
interchangeably, but they are different. A class is the code that you write up. There
will be only one soldier class (assuming that all of the soldiers are the same).
However, there may be many soldier objects. Each instance of the soldier class is
another object. For example, when the prince reaches the tower, your program
creates five soldiers to block him and try to kill him. Each one of those soldiers are
an object of class soldier. When you fight them, one soldier object might have five
hits left, one may have three, and one may be dead. Another example in the real
world. There is one class of Toyota Camry. However, there are thousands of
Toyota Camry objects, as I am currently driving one, my neighbor has one in his
driveway, and I just saw one that got into a crash down the block. Although we're
all part of the Toyota Camry class, we each have an independent object. Back to
the Prince game. The game has a main class, that runs the game. There is also a
prince class and a soldier class. Lets say in the game, when the prince reaches the
tower, five soldiers come out (like before). In the main class, you will write code
that says if the prince reaches the tower, instantiate (meaning create an instance or
Object of) one soldier calling it soldierOne, a second soldier calling it soldierTwo,
etc, and tell each one to attack the prince. This helps writing your code in many
ways. First of all it helps mimic real life, enabling you better to visualize how to
write it. Second, it makes writing the code real easier. I need to only write the code
for soldier once, with all of its complicated methods, and whenever I want one, I
just tell the main program to create a new object of that soldier, and put it here. I
don't need to worry about telling one soldier to now swing at the prince, one
soldier to now jump, etc. The program will do that automatically, as I had
instructed in the soldier class. Each object of that soldier will follow all of the
rules that the soldier class has, all I need to do is tell the main program, put one
here, put one here.

Great, you'll say, that helps me to visualize the program better, and I can even see
how this will help keep my errors down and make my debugging easier. But, it
doesn't help with the problems that you started with. Your program works well if
there is only one kind of soldier. Lets say you want there to be different kinds of
soldiers, and each one does something slightly different. You're going to have to
write many of the same lines of code many times for each different soldier class,
and your going to have all of the maintenance problems that you discussed in the
beginning. The answer to that is "No", Java and Object Orientation take care of
that also. They do it with something known as inheritance. Inheritance means that
the child class can inherit, and get everything that is in the parent class
automatically. The most well used example is that of a car. Almost every car is
similar, with a few exceptions. If you were writing code for a car, you would have
methods like openDoor(), drive(), brake(), rollDownWindow(), etc. Lets say that
this code has 200 methods, and took 1800 lines of code (not to mention a week).
Now, you have to write the code for a convertible. The only difference between a
convertible and a regular car is that the convertible's roof can come down. If you
had to cut and paste all of the code from the car class, then yes you would have all
of the problems. But, you can write in your code I want the class of Convertible to
extend and inherit everything from class Car, and automatically class Convertible
will have all of the methods and data from class Car. The code for Convertible will
have written inside of it only one method, openRoof(), will be only 100 lines of
code, but will be able to do all 200 methods of class Car. Even if you need a
second car that drives differently you can say that the Car2 extends everything
from Car, and write one method called drive(). Since the child class (Class2)
extends class Car, it will automatically have all 200 methods. However, since it
has one method with the same name as the parent class, the computer will ignore
the parent's method of drive(), and only use Car2's new method of drive(). In our
Prince game, you can create a class called BadGuy, that has certain methods and
data that every single enemy in the game will have. Then you can have one class
called Skeleton that will have only the special and different methods that skeleton
will have, and one called Soldier, that will have its special methods. Then, both
class Skeleton and Soldier will automatically have every method that class
BadGuy will have, and whatever they added. You can even make two classes
called StupidSoldier and FastSoldier that have minor differences, and have each
one inherit from class Soldier, and add their own minor differences. That way, if
you have to change a piece, you only need to change it in one place, and every
class that depends on that piece will now change. This is somewhat of an
oversimplification, but the main purpose of this page is to give an understanding
of the topic, and not go into details of how it works.
So far we discussed two ways to have a class relationship. It can be a "stand alone"
class that doesn't inherit from any class, or you can have one class inherit from
another. Another way, is for one class to contain inside it another class. For
example, You can have a Car class, a Wheel class, and a Door class. The Car class
will have inside it four Wheel objects, and four Door objects. You can have a
FramedWondow Class that will have inside it a few Button classes. You write the
code for a Button class, and you tell the FramedWindow to contain that Button by
instantiating and placing inside that Button. In these examples, one class has a
second class inside it.

I am now going to give a second example of inheritance. In programming, there


are many kinds of popup windows, each containing buttons and other stuff, that
are needed often. Therefore, Java created them for you automatically, and all that
you have to do is instantiate (tell the program, create an object of this kind of
window here) them. (See the API section for details.) In Java's graphic package
there's a class called Window, that when created pops up a simple window. There
are two classes that need everything that Window have, and more; Dialog and
Frame.

Class Frame needs whatever Windows has, plus the icon, the ability to add a menu
bar, the boxes in the corner to enlarge, make small, and close, etc. Class Dialog
only has the icon and the box to close. However, Dialog has something that Frame
doesn't, the ability to freeze every other window besides for itself. Therefore, you
don't want the Frame to inherit from Dialog because Dialog has the ability to
freeze the other windows, and you don't want Dialog to inherit from Frame,
because Frame has a whole lot more than Dialog. However, most of the code is
exactly the same, and to cut and paste would be wasting a lot of code. The answer
is simple. Create a class that has whatever both Frame and Dialog both have in
common, and each one will inherit that class and add what they have individually.
This is what Java has done for you already, by creating a Window class, and
having both Frame and Dialog inherit from Window, and add their individual
methods. This is inheritance, as now both Frame and Dialog are really a Window
with added features.
Containment would be for class Frame to contain and have inside it other classes.
Java has premade classes like Button, Label, TextField. In the following picture,
you see a Frame that has Buttons, Labels and TextFields. Just Like a Car has a
Door, so too one Java class can have inside it another Java class. And in reality,
The Prince of Persia game uses containment, because the main program had inside
it both the prince and all of the soldiers. All the Prince of Persia had to do was
write create a new soldier here, create a new soldier here, and the main program
will now have inside it a new soldier object.

One last example of inheritance. By Java's premade Frame class, if you hit the
little close box in the corner, nothing happens. Java did this so that you can have
more control of your Frame, but it is extremely annoying. All that it would have
taken Java to do in order to close the Frame would have been to add 5 lines of
code, but now you are stuck with a Frame that doesn't close. But not to worry. You
can inherit the Frame class, and add those five lines. You can wrote a program that
will now be only 10 lines which you can call ClosableFrame, which all that will be
in the code is ClosableFrame should inherit everything that is in Frame, but add
that when the close box in the corner is hit, the Frame will close, and your new
class of ClosableFrame will have everything that its parent Frame class has, plus it
will close, with only a few lines of code.

Advanced Topics

These topics are extremely advanced, have many books written on each one alone,
and you can usually find college classes on some of these. I'm not going to explain
here how you use these, but mainly what they mean, and why you need them.

Exception Handling: The purpose of exception handling is to enable that when


something out of control goes wrong, that the program does not crash, by either
righting itself, or at least if necessary, by dying gracefully. A well used example is
the following. You ask the user to type in a number. The user types in "8d7r".
Your program tries multiplying this number, and can't. If you did not have
exception handling, then the program would crash. What else is it supposed to do.
Therefore you use exception handling and say like this. "If anything between (lets
say) lines 25 through 78 cause an error, instead of crashing, run this fixup code".
This is known as a try catch block. You tell the computer to try to do lines 25 - 78,
and catch the following errors. If the computer does catch them then it should do
the following to fix it. In my case you would say, "if you catch a 'Number is
messed up, and not really a number' exception, then show a window saying, 'You
idiot, please type in a real number'". You can catch a specific error, or say "catch
any and every error". You can also catch one error after another and say, "If you
catch error one do this, error two do that, and error three don't do anything, and if
another error that I didn't mention happens, then do this." (Obviously, this is not
how you code it, but I'm trying to show the idea).

Exceptions

A Java program should never "core dump," no matter how buggy it is. If the
compiler excepts it and something goes wrong at run time, Java throws an
exception. By default, an exception causes the program to terminate with an error
message, but you can also catch an exception.

try {
// ...
foo.bar();
// ...
a[i] = 17;
// ...
}
catch (IndexOutOfBoundsException e) {
System.err.println("Oops: " + e);
}
The try statement says you're interested in catching exceptions. The catch clause
(which can only appear after a try) says what to do if. In this case, we print an
error message. The toString() method of an exception generates a string containing
information about what went wrong, as well as a call trace.

WARNING Never write an empty catch clause. If you do, you will regret it.
Maybe not today, but tomorrow and for the rest of your life.

Because we caught this exception, it will not terminate the program. If some other
kind of exception occurs (such as divide by zero), the exception will be thrown
back to the caller of this function and if that function doesn't catch it, it will be
thrown to that function's caller, and so on back to the main function, where it will
terminate the program if it isn't caught. Similarly, if the function foo.bar throws an
IndexOutOfBoundsException and doesn't catch it, we will catch it here.

The catch clause actually catches IndexOutOfBoundsException or any of its


subclasses, including , and others. An Exception is just another kind of object, and
the same rules for inheritance hold for exceptions as any other king of class.

You can define and throw your own exceptions.

class SytaxError extends Exception {


int lineNumber;
SytaxError(String reason, int line) {
super(reason);
lineNumber = line;
}
public String toString() {
return "Syntax error on line " + lineNumber + ": " + getMessage();
}
}
class SomeOtherClass {
public void parse(String line) throws SyntaxError {
// ...
if (...)
throw new SyntaxError("missing comma", currentLine);
//...
}
public void parseFile(String fname) {
//...
try {
// ...
nextLine = in.readLine();
parse(nextLine);
// ...
}
catch (SyntaxError e) {
System.err.println(e);
}
}
}
Each function must declare in its header (with the keyword throws) all the
exceptions that may be thrown by it or any function it calls. It doesn't have to
declare exceptions it catches. Some exceptions, such as
IndexOutOfBoundsException, are so common that Java makes an exception for
them (sorry about that pun) and doesn't require that they be declared. This rule
applies to RuntimeException and its subclasses. You should never define new
subclasses of RuntimeException.

There can be several catch clauses at the end of a try statement, to catch various
kinds of exceptions. The first one that "matches" the exception (i.e., is a super
class of it) is executed. You can also add a finally clause, which will always be
executed, no matter how the program leaves the try clause (whether by falling
through the bottom, executing a return, break, or continue, or throwing an
exception).

Multithreading Multithreading means having a single process (program) doing


many things at the same time, while sharing the general data. Why would I want
this, and any ways, what does it mean? A computer can only do one thing at a
time. However, computers are so fast, that it can do part of one program in lets
say, one tenth of a second, clear and save all of the memory for that program,
work a second program for one tenth of a second, etc. Then in one second ten
programs could work consecutively, and it will look like the computer is doing all
ten in one shot. This is known as multiprocessing, meaning a bunch of completely
separate programs running at the same time. But, lets say that you want one
program to run different parts at one time. Why would I want to do that? Look at
Microsoft Word. They have one piece of code to check for spelling, one piece of
code to check for grammar, one piece to allow you to type, and the piece of code
to run that annoying little paperclip in the corner, All at the same time. That's
multithreading. For the same program to create "threads" that do different things
together. Not that a computer can do more than one thing at a time, but it keeps on
switching from one piece of code to the next, so fast, that it looks like it is all
happening at the same time. The difference between multiprocessing, and
multithreading, is that multiprocessing is running different programs, while
multithreading is running different threads in one program. Therefore,
multiprocessing has to clear what it is working in the processor (the part of the
computer's brain that runs the instructions) and save it for next time, while
multithreading keeps the same program, and just runs different parts. Another
example of multithreading is the computer game of diablo (or any advanced
computer game). You're inside the ruins, and ten skeletons, five bats, and three
ogres come to attack you. How is the computer able to run through each one?
Through multithreading, the program can give a different thread to each one, and
switch off to give a thousandth of a second for each one. Therefore, it looks like
they (and you the sorcerer) are all running at exactly the same time, but in reality,
the computer is switching off. Also, since they all have to interact with each other,
with you, and with the rest of the game (like if you fire at him he dies), so you
don't want to clear the basic memory every time, but that they should all run with
the same memory together.

In Java, multithreading is very easy. You just tell the program that you want it to
be a thread, and when you want the thread to start, you tell it to start. The
switching back and forth is all done for you by the Java language automatically.

Threads

Java lets you do several things at once by using threads. If your computer has
more than one CPU, it may actually run two or more threads simultaneously.
Otherwise, it will switch back and forth among the threads at times that are
unpredictable unless you take special precautions to control it.

There are two different ways to create threads. I will only describe one of them
here.

Thread t = new Thread(command); //


t.start(); // t start running command, but we don't wait for it to finish
// ... do something else (perhaps start other threads?)
// ... later:
t.join(); // wait for t to finish running command
The constructor for the built-in class takes one argument, which is any object that
has a method called run. This requirment is specified by requiring that command
implement the Runnable interface described earlier. (More precisely, command
must be an instance of a class that implements Runnable). The way a thread "runs"
a command is simply by calling its run() method. It's as simple as that!
you are supposed to run each command in a separate thread. Thus you might
declare something like this:

class Command implements Runnable {


String commandLine;
Command(String commandLine) {
this.commandLine = commandLine;
}
public void run() {
// Do what commandLine says to do
}
}
You can parse the command string either in the constructor or at the start of the
run() method.

The main program loop reads a command line, breaks it up into commands, runs
all of the commands concurrently (each in a separate thread), and waits for them to
all finish before issuing the next prompt. In outline, it may look like this.

for (;;) {
System.out.print("% "); System.out.flush();
String line = inputStream.readLine();
int numberOfCommands = // count how many comands there are on the line
Thread t[] = new Thread[numberOfCommands];
for (int i=0; i<numberOfCommands; i++) {
String c = // next command on the line
t[i] = new Thread(new Command(c));
t[i].start();
}
for (int i=0; i<numberOfCommands; i++) {
t[i].join();
}
}
This main loop is in the main() method of your main class. It is not necessary for
that class to implement Runnable.

Although you won't need it for project 1, the next project will require to to
synchronize thread with each other. There are two reasons why you need to do
this: to prevent threads from interferring with each other, and to allow them to
cooperate. You use synchronized methods to prevent interference, and the built-in
methods to support cooperation.
Any method can be preceded by the word synchronized (as well as public, static,
etc.). The rule is:

No two threads may be executing synchronized methods of the same object at the
same time.

The Java system enforces this rule by associating a monitor lock with each object.
When a thread calls a synchronized method of an object, it tries to grab the object's
monitor lock. If another thread is holding the lock, it waits until that thread
releases it. A thread releases the monitor lock when it leaves the synchronized
method. If one synchronized method of a calls contains a call to another, a thread
may have the same lock "multiple times." Java keeps track of that correctly. For
example,

class C {
public synchronized void f() {
// ...
g();
// ...
}
public synchronized void g() { /* ... */ }
}
If a thread calls C.g() "from the outside", it grabs the lock before executing the
body of g() and releases it when done. If it calls C.f(), it grabs the lock on entry to
f(), calls g() without waiting, and only releases the lock on returning from f().

Sometimes a thread needs to wait for another thread to do something before it can
continue. The methods wait() and notify(), which are defined in class Object and
thus inherited by all classes, are made for this purpose. They can only be called
from within synchronized methods. A call to wait() releases the monitor lock and
puts the calling thread to sleep (i.e., it stops running). A subsequent call to notify
on the same object wakes up a sleeping thread and lets it start running again. If
more than one thread is sleeping, one is chosen arbitrarily no threads are sleeping
in this object, notify() does nothing. The awakened thread has to wait for the
monitor lock before it starts; it competes on an equal basis with other threads
trying to get into the monitor. The method notifyAll is similar, but wakes up all
threads sleeping in the object.

class Buffer {
private List queue = new ArrayList();
public synchronized void put(Object o) {
queue.add(o);
notify();
}
public synchronized Object get() {
while (queue.isEmpty()) {
wait();
}
return queue.remove(0);
}
}
This class solves the so-call "producer-consumer" problem. (The class ArrayList
and interface List are part of the java.util package.) "Producer" threads somehow
create objects and put them into the buffer by calling Buffer.put(), while
"consumer" threads remove objects from the buffer (using Buffer.get()) and do
something with them. The problem is that a consumer thread may call Buffer.get()
only to discover that the queue is empty. By calling wait() it releases the monitor
lock and goes to sleep so that producer threads can call put() to add more objects.
Each time a producer adds an object, it calls notify() just in case there is some
consumer waiting for an object.

This example is not correct as it stands (and the Java compiler will reject it). The
wait() method can throw an InterruptedException exception, so the get() method
must either catch it or declare that it throws InterruptedException as well. The
simplest solution is just to catch the exception and print it:

class Buffer {
private List queue = new ArrayList();
public synchronized void put(Object o) {
queue.add(o);
notify();
}
public synchronized Object get() {
while (queue.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return queue.remove(0);
}
}
The method printStackTrace() prints some information about the exception,
including the line number where it happened. It is a handy thing to put in a catch
clause if you don't know what else to put there. Never use an empty catch clause.
If you violate this rule, you will live to regret it!

There is also a version of Object.wait() that takes an integer parameter. The call
wait(n) will return after n milliseconds if nobody wakes up the thread with notify
or notifyAll sooner.

You may wonder why Buffer.get() uses while (queue.isEmpty()) rather than if
(queue.isEmpty()). In this particular case, either would work. However, in more
complicated situations, a sleeping thread might be awakened for the "wrong"
reason. Thus it is always a good idea when you wake up to recheck the condition
that made to decide to go to sleep before you continue.

Input Output (IO or I/O) Input means what comes into your program from the
outside, and output means what is going to leave your program to the outside. For
example, if you want your program to read what the user has typed in from the
keyboard, or read from a different file, then you need to input that information. If
you want that your program should send a paragraph to the printer to print, the
screen to display, or to some other file to be stored, then you need to output that
paragraph. Java supplies many classes and ways to input and output. They supply
ways to input and output characters, streams, files, and serialized objects.
Characters are like Strings, meaning, that it will input/output a bunch of characters
that make up words and sentences. Streams are streams of bytes. Since everything
deep down in the computer world is composed of ones and zeros, you can send a
stream of ones and zeros to be outputted (for example) to the screen. (If you open
a picture with certain editors, like TextPad, you will see that that picture is made
of ones and zeros (although in a 16 number digit system)). Files are whole records
of data, like a file on your computer, or like a folder in your file cabinet at home.
Serializable objects are objects that the program can save the way it is with the
behavior that it currently has, and reput it together in exactly the same way. This is
known as serializing, and deserializing. One other word that comes up a lot is a
buffer. A buffer is a storage space of memory that a large amount of data can be
placed into, and outputted at once. For example, lets say you have a program that
makes up a word, and outputs it. If you only need the end product, then it's a waste
to send each word separately. Instead, you put all of the words into a big chunk
called a buffer, and when the buffer becomes full, you send the whole buffer as
one big piece of data.
Input and Output

Input/Output, as described in Chapter 15 of the Java book, is not as complicated as


it looks. You can get pretty far just writing to System.out (which is of type
PrintStream ) with methods println and print. For input, you probably want to
wrap the standard input System.in in a BufferedReader , which provides the handy
method readLine()

BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
for(;;) {
String line = in.readLine();
if (line == null) {
break;
}
// do something with the next line
}

If you want to read from a file, rather than from the keyboard (standard input), you
can use FileReader, probably wrapped in a BufferedReader.

BufferedReader in =
new BufferedReader(new FileReader("somefile"));
for (;;) {
String line = in.readLine();
if (line == null) {
break;
}
// do something with the next line
}
Similarly, you can use new PrintWriter(new FileOutputStream("whatever")) to
write to a file.

Integer, Character, etc.


Java makes a big distinction between values (integers, characters, etc.) and objects.
Sometimes you need an object when you have a value (the next paragraph has an
example). The classes Integer, Character, etc. serve as convenient wrappers for
this purpose. For example, Integer i = new Integer(3) creates a version of the
number 3 wrapped up as an object. The value can be retrieved as i.intValue().
These classes also serve as convenient places to define utility functions for
manipulating value of the given types, often as static methods or defined
constants.

int i = Integer.MAX_VALUE; // 2147483648, the largest possible int


int j = Integer.parseInt("123"); // the int value 123
String s = Integer.toHexString(123);// "7b" (123 in hex)
double x = Double.parseDouble("123e-2");
// the double value 1.23
Character.isDigit('3') // true
Character.isUpperCase('a') // false

Character.toUpperCase('a') // 'A'

Networking Networking in short (as this is a major subject) is the ability for one
computer to talk to another through a connection. For a network you need two
things. One is the physical device that connects the two computers, and the second
thing that you need is the code that enables one computer to call and talk to
another. In networking you have two parties, the client and the server. The server
starts and waits for someone to call him. The client calls him, and the server
answers back. For example, lets look at the Internet. The web browser (like
Internet explorer) makes a call to the web server, giving it an Internet address, and
asking it to return the page that that address points to. The web browser is a client,
asking for information that the web server will return. The server is running even
if no one is online, waiting for someone to call it, and the client makes that call,
expecting the server to be there. The physical medium for the computers to talk is
the phone wire, and the other part is the web browser and web servers' software.
Another way of networking is through an intranet. An intranet is a bunch of
computers, networked together, that they and only they can talk to each other, but
no one from the outside can get in. A company might have an intranet where they
can share information between each other, but not to someone from the outside.
Here, the physical medium are the wires that connect the computer's together, and
the logical medium is the software.

Like the other technologies, Java does most of the work of networking for you.
Java creates something called sockets, that allow you to talk to a different
computer through inputs and outputs.
API's and Javadoc: What are they?

(This section should be read only after reading the Object and Class section, as it
constantly mentions words like classes, interfaces, etc. without explaining them.
An interface, in short, are a bunch of empty methods, that you or someone else
must fill in.)

An API stands for a "Java Application Programming Interface". It is like a super


dictionary of the Java language, that one uses to look something up in. It has an
index or collection of all Java packages, classes and interfaces, with all of their
methods, fields and constructors, and how to use them. When one programs, there
are many classes that are commonly used, and therefore pre created, so that the
programmer doesn't need to create them from scratch. Let's look, for example, at a
computer window frame. If the programmer had to create one from scratch, he
would have to write hundreds of lines of code, to create the scroll down menu, the
exit box, etc. Since a window frame is very popular, Sun has written the code for
one, and all that you have to do is import the package that contains the window
frame, and instantiate one with a new statement.

As with all of Sun's classes, we do not care how it is implemented, all we need to
know are what the methods are, the constructors, and it's fields. Hence the name
Java Application Programming Interface, the API is a collection of interfaces
telling us what each class can do, not telling us how it is done. The API contains
many packages for many different purposes, among them, the applet package for
creating applets, the awt and swing packages for graphics and GUI, the io package
for input and output, the sql package for Java databasing, and many many more.
For every package that you use a class from you must import it, with the exception
of the java.lang package that deals with basic programming classes, that is
automatically imported into your program.

Each API is organized in the following way. When you start the API you are given
three frames, the first listing all of the Java packages in that API, and when you
click on any particular package, the second frame lists all of the interfaces, classes,
and exceptions in that package. The main frame starts with an overview of all of
the packages, and shows the index, class hierarchy for each package, and help
section when you click for it on the top menu. Also, it gives you the details for
each class document. The Index contains an alphabetic list of all classes,
interfaces, constructors, methods, and fields. The class document is set up with the
top showing that class inheritance diagram and subclasses, the middle showing the
field, method, and constructor summaries, and the bottom giving details for the
fields, methods, and constructors. For more information, check out the APIs help
section.
In short, when you start programming, you're constantly going to have to look up
something in the API. There's going to be some class or method that you don't
know how to use, you're not sure what parameters it takes, etc, and you can find
out all of the information in the API. When Shlomo started writing Java, a certain
program always crashed during some String methods, and Shlomo spent hours
trying to figure it out unsuccessfully. Finally someone looked up the String
methods in the API, noticed that the method substring() was spelled substring()
instead of the assumed subString(). Well, Shlomo was extremely impressed, until
he himself figured out how to use the API, and realized how easy it was.
To find out how to download the different APIs go to my Java API section. (yes, I
reused the explanation of what an API is from there).

Javadoc is the ability to create these API looking documents out of your own
code. When you write your code you place html tags and javadoc tags in special
comments (that look like this)
/**
* place comments here
*
*/.
These comments you place before the beginning of the code for your class, and
before most of your methods. Then instead of typing in java or javac on the CMD
console, you type "javadoc nameOfClass " or "javadoc NameOfPackage". The
compiler will then create an html document, that explains your methods, fields and
constructors, plus whatever HTML that you added, in the same exact way that the
API looks.
For more information on javadoc, check out Sun's official tool section .

Das könnte Ihnen auch gefallen