This tutorial is divided into sections. If
you want to jump to one of these sections, just click on the link
below.
This
tutorial is divided into sections. If you want to jump to one of
these sections, just click on the link below.
Introduction
Java
is definitely one of the most popular programming languages now, and
not only that, it is one of the few programming languages with the
kind of frameworks and packages that can serve at an enterprise
level. By no means that
kind of high capability indicates complexity of the programming
language itself, and in fact, Java is very easy to learn and
comprehend, regardless whether you have done programming in other
languages, or you have not done any computer programming at
all. At the end of this
tutorial, you will find out why Java is so simple, yet so
powerful.
API
The very key concept about Java, and a lot of
programming languages, is called Application Programming Interface,
aka API.
I know I started to throw in some acronyms already. When
you have to deal with or talk about something so many times, you
would too prefer a quicker way to refer to it. Yes,
all the acronyms I use in this tutorial will be used by Java
developers many many times. So, think about the positive side
of acronyms, and start to use them too.
Back to the API topic, it is the real glue that
keeps every individual piece of code together inside Java
programs.
I'm sure you have heard people say that Java is an object
oriented programming language. Here's a simple way to understand
that notation. Every piece of Java code, whether
you wrote it or the folks who created the JDK wrote it, can be
compared to the design of an object, such as an electric outlet you
see every day inside your house; there's an interface facing the
outside, here we call it public interface, and there's all the ugly
wirings inside the wall, which we call the implementations. No
doubt that for a particular piece of Java code to be used by other
code pieces, its public interfaces are definitely the connection
points, and should be clearly defined and published. As for
the implementations, since they are hidden and not exposed, you have
many ways to get them to work, as long as they eventually provide
the actual functionalities to support what the public interfaces
promise to the outside world. These public interfaces are what
APIs refer to.
So to a large extend, it's all about public
interfaces and internal implementations.
Sounded simple, right?
However, those two things play the most important role in
separating the seasoned Java developers from novice or non seasoned
Java developers. How's so? Think
about the electric outlet concept again. If the
public interface that everyone depends on is not well designed or
defined, it may confuse people as for how to use the whole
thing.
Or, it may be defined OK, but not well thought through, and
has to be changed over time for many times, therefore whoever uses
it is forced to change their way of using it accordingly every time
the interface changes. It's not a good interface in
those cases, and the problems can and should be avoided. On the
other side, even though the implementations are not exposed, and can
be as ugly as they get, a clean and efficient inside wiring will
definitely make future maintenance way much easier. The
point to make here is, that even though you are just starting to
learn Java, keep in mind about these two important things along your
way, and they will help you become a seasoned developer much
faster.
Setup
To do our first Java program, all we need is a
text editor to write our code with, and a Java development kit, aka
JDK, to compile our code before we run it.
However, like I said that APIs are the glue
inside Java programs, it is inevitable that we need to use other
people's code inside our code through their published public
APIs.
Can you imagine how many API definitions we can use? Yes,
that is a lot, and nobody wants to or needs to remember them
all.
How do we do the job then? Pick a good tool. A good
tool can show, with a simple keystroke, all the available interfaces
provided by any piece of code as part of the core JDK, or code
created by your peers or even yourself. We call
this kind of tools IDE, Integrated Development Environment. A very
popular and powerful IDE available currently and for many years
already is called Eclipse. It is Free!
So we go to this website to download the latest
version of Eclipse, http://www.eclipse.org, and this
website to download the latest JDK under Java SE, http://java.sun.com.
Install JDK first, then the IDE. Here's
the first screen you will see after you run Eclipse from your
computer.

The few links in the center of the area will
take you to some tutorials and examples etc, which you are
encouraged to explore. To quickly complete our first
Java program, let's click on the right most link which says
Workbench when you move your mouse over it.
First Program
With everything setup, we can start writing our
first piece of code. A piece of Java code is really
called a class. When we
run our class, we create an instance of
it, and then we operate on its public interfaces. In
other words, a class is like some specifications we write or a
blueprint we draw on a piece of paper, for our electric outlet as an
example, and an instance of it is like a real object created,
according to this set of specifications. We can
surely create multiple instances or objects out of one particular
class, and those instances are individual entities, even though they
all follow the same specifications. Changing one instance will not
affect any other instances at all.
For our first program, let's design a mobile
phone simulator, a class called Phone. The
first thing to think about for this design is, you guessed it, the
public interfaces we will provide to the outside world.
Obviously, we need some buttons, like power button, talk
button, hang up button, and all the number buttons from 0 to 9,
etc.
Here's what they will look like in our class definition -
public void pressPower() { }
public void pressZero() { }
…
public void pressTalk() { }
public void pressHangUp() { }
The word public
tells the compiler that we are defining a public interface for other
classes to use, and the word void says
that we do not return any value after these methods are
executed.
Of course we need to write code inside these methods to
actually do something, and the code we write inside are the
implementations. During our implementation, we
very frequently will run into situations when we want to create some
code that can be shared by many methods, but not intended to be
exposed to the outside world. This is when we need to create
some private methods. Here's
a good example, which will print out what's currently on the phone
screen.
We will use it at the end of each public call to show what
just happened to the phone -
private void display(String message) { }
From the above line, you see I introduced a way
for passing in different values to a method.
Specifically, the portion that says String message inside the brackets serves
this purpose. Callers of this method have to provide that value.
As part of the internal implementations, we
also need to keep the states of a phone, such as whether the phone
is turned on or off, and what buttons the user has pressed so far,
etc.
This is when we need to create some member variables. In our
case, they should be defined as private as well, so that they won't
be accidentally modified by other classes -
private boolean powerStatus;
private String buffer;
Here again the first word describes whether it
is exposed to the outside world or not, but the second word is the
data type for each variable we are defining. A boolean variable has two values, true and
false, with false as the default value if not clearly set yet. String is a quite frequently used JDK
defined class, and needs to be properly set with a value first
before we use it. If users want to change their
value, they have to go through the public interfaces. For
example, calling this following interface and implementation will
toggle the power status -
public void pressPower() {
if (powerStatus == false) {
powerStatus = true;
} else {
powerStatus = false;
}
}
In the previous code example, we just
introduced the usage of curly brackets, for marking code blocks, and
semicolons, for marking the end of each statement. This
method simulates the press of the power button. By
checking the current value of the powerStatus variable, we can find
out the current power status of our phone. When true is the value detected in the variable,
we know the power is current on, and pressing the button now will
turn the phone off, and a status of false will be stored in the powerStatus
variable.
Vice versa.
Now it's time for us to pull out the Eclipse
again, and type in the code we just discussed. After
you click on the Workbench link, you will see a screen with many
small panels. From the main menu, select File, new, project..., and then from a pop up dialog,
select Java Project under Java.

Click on Next to go to next dialog, and provide
a project name. Here we can call it PhoneSimulator.

Click on Finish, and answer Yes to the next question regarding Open Associated Prospective.
Now we have our project setup, and ready to put
in our first Java class. From the Package Explorer on the top left hand side
panel, click on the + sign in front of
the PhoneSimulator project name, and
right click on src, select New, and then Class. On the next pop up dialog,
type in com.mycompany as the Package name, and Phone as the Name of the class, then click on Finish.
Here's where we are now -

In implementing the internal display method, we
need to rely on an existing JDK functionality for printing something
onto the screen, specifically System.out.println. Here's
the part where IDE helps us tremendously; as soon as you type in the
dot after System, a drop down list box
will come out in the editor, to show you all the APIs you can
select.

In this case, we select out. As soon as we type in a dot after
out, we see another list comes out -

In this case, we select println. In stead of making a selection
from the list box right away, you can also keep typing in the
characters you know about, like pr, and
it'll keep narrowing down the selections in the list. What a
handy tool! That makes it so much easier to
navigate among all the available APIs you can use.
Here's our completed Phone class
definition. To save some space, I did leave
out some obvious methods that you can fill out very easily on your
own.
Make sure you fill them up before running this.
package com.mycompany;
public class Phone {
// define member variables first
private boolean powerStatus; // to keep track of power status
private String buffer; // to keep
track of the buttons user has pressed
// define a constructor, which will be called
every time when a new instance is created; a good place to
initialize our variables
public Phone() {
powerStatus = false;
buffer = "";
}
// define public methods
public void pressPower() {
if (powerStatus == false) {
powerStatus = true;
} else {
powerStatus = false;
}
display("The power is " + (powerStatus?"on":"off"));
}
// dial whatever number user has pressed so far
public void pressTalk() {
display("Dialing " + buffer);
}
// hang up button will also clear the key
buffer
public void pressHangUp() {
buffer = "";
display("Hung up");
}
public void pressZero() {
buffer = buffer + "0";
display();
}
public void pressOne() {
buffer = buffer + "1";
display();
}
// Please fill out the implementations for press 2, 3, 4, 5,
6, 7, 8, 9
// …
// define internal methods
private void display(String message) {
System.out.println(message);
}
// Over loaded method to work differently
because of the different parameter signature
private void display() {
display(buffer);
}
}
A couple of more things introduced here. First,
every line that starts with // is a comment line, and will be
ignored by the compiler. Then the constructor
concept.
A constructor is a special method that gets called every time
when a new instance of this class is instantiated. In most
cases, you need to declare it as public, and make sure it has no
return type, and shares the same name as the class name. You may
also have noticed that I added another display method besides the
one we talked about already, however without a parameter inside the
brackets.
This is called method overload, which as the example
indicated requires different kinds of parameter signatures. In our
case, if the message parameter is not provided, the new display
method will be called instead, and in turn it calls the original
display method using the buffer as the parameter. In
plain English, if we don't tell it what message to display, it
displays the buffer content.
Use It
Now we can do some exercises on this newly
create phone class. To actually use the Phone class,
we will create another class called User. Since
our illustrations focus on the Phone class, we will simplify the way
we use this User class, and put everything inside the special main method.
Again from the Package
Explorer panel, right click on com.mycompany under src under PhoneSimulator. Select
New and Class. From the pop up dialog, type in
User as the class Name, and check the check box labeled public static void main(String[]
args). Then Finish. A new bare bone class will be
created.
The main method is a special method, because it
is the entry point of every program. Make sure you use it in the one
entry class among all the classes in your project, without changing
any part of its signature.
Then we instantiate a Phone object using the
following syntax, and assign it to a variable called myPhone. We will
be doing some operations on this myPhone object.
Phone myPhone = new Phone();
So what can we do to this myPhone object? You got
it.
All the public interfaces we defined for the Phone class will
be available for us to call. Do you remember all of them? No need
to, because we have our super IDE. Same way as how we triggered the
drop down list earlier, here we go with a simple dot after myPhone
variable, or by pressing control+space key.

From the list, do you see the public methods we
created earlier inside the Phone class? We can
call any one of them now, without having to care about how they were
implemented, or how they were internally wired.
Ok, I added a few more operations on this
myPhone object, and here's a complete list of the User class.
package com.mycompany;
public class User {
/**
* @param args
*/
public static void main(String[] args) {
// create a phone object from Phone class
Phone myPhone = new Phone();
// turn it on
myPhone.pressPower();
// press 9721112222 in sequence
myPhone.pressNine();
myPhone.pressSeven();
myPhone.pressTwo();
myPhone.pressOne();
myPhone.pressOne();
myPhone.pressOne();
myPhone.pressTwo();
myPhone.pressTwo();
myPhone.pressTwo();
myPhone.pressTwo();
// press talk button
myPhone.pressTalk();
// then hang up
myPhone.pressHangUp();
// turn it off
myPhone.pressPower();
}
}
Now right click any where inside the editor
loaded with User.java, and select Run
As, then Java Application. Here's
what you will see from the output console -

What's Next?
By now you have successfully created some Java
classes, and hopefully obtained some good understanding of what APIs
imply from our simple example. A lot of focus has been put on
explaining the API concept, because everything complicated in Java
is built upon it. From the core JDK, to the
code written by your peers or even yourself, to the enterprise level
frameworks and packages, APIs are always the key to communicate the
things they can do. Because of our handy dandy IDE,
you should have no worries about the vast amount of APIs out
there.
Throughout this tutorial, I intentionally
avoided burdening you with all the fine details about Java. Among
the things I did not talk about, some are critical for you to
understand, such as P.I.E. – Polymorphism, Inheritance,
Encapsulation. Here is a very popular Java
introductory book Beginning Java Objects: From Concepts to
Code by Jacquie Barker.
To user Eclipse more efficiently, you may go
through the built-in tutorials and examples inside Eclipse.
In order not to make my example too
complicated, I have violated some best practices. For
example, the buffer variable should be
defined as a StringBuilder instead of a simple String, so as to
avoid excessive memory usage introduced by excessive String
concatenations (+). This brings up my next
suggested reading Refactoring: Improving the Design of Existing
Code (Addison-Wesley Object Technology Series) by Martin Fowler, Kent
Beck, John Brant, and William Opdyke . This book will help you start
coding in Java the right way right away!
|