Building Your First Java Program: Starting From Scratch
Welcome to CS 1331! If this is your first time using a corporate-grade
programming language, then you will probably find this tutorial
quite useful! The point of this guide is to familiarize you
with the basic workings of Java enough to allow you to install
and configure the Java Virtual Machine, set up any path settings,
and setup an Integrated Development Environment (IDE) to then
write the actual Java code. Hopefully, this will give you enough
knowledge and elbow room to experiment and learn more about
Java on your own. Good luck!
Java Installation Overview |
(Win) (Mac) |
Configuring the Java Virtual Machine |
(Win) (Mac)
|
Overview and Installation of IDEs |
(Win) (Mac)
|
Writing a Java Class |
(Win) (Mac)
|
Compiling / Running your Java code |
(Win) (Mac)
|
Conclusion |
(Win / Mac) |
Java Installation Overview - Windows
This part will cover installation of the newest version of
Java, 7.0, on your
computer. Note that it will be
OK to have version 6 for our
class as well, but not 5 or
earlier. So first you must check
to be sure that you have no
previous (5 or earlier) version of Java installed
and, if you do, you must uninstall it before continuing. So
first we will check for previous installations.
Let's begin by opening up your Control Panel. Double click
on "My Computer", and from the menu along the left panel of
the window, select "Control Panel."
Important! Once the Control Panel comes up, check the left
panel again. If there is an option there called "Switch to Classic
View," select it now. Otherwise, if it says "Switch to Category
View," leave it alone.
Now, select the "Add or Remove Programs" icon from the list
- it should be one of the first couple ones across the top.
From the list of programs that then pop up, scroll downward
and look for any program(s) with the name "Java SE Development Kit" in it. If you
find one or more, note the version number. If the version number
is 5 or less, you will need to uninstall those Java programs before continuing.
You can do this by selecting the programs and clicking the "Change/Remove"
button that appears and following the directions. If the version
number is 6 or 7, then you can skip the rest of this installation
chapter, as you have a new
enough version of Java running
for our class! (Note that if
you have version 6, you just
might want to uninstall it and
change over to the newer
version 7.) If
there is no Java installation listed, or you have already uninstalled
a previous installation, simply keep reading!
The next step will be to download Java itself! You have a
few options on where to locate a working copy of Java. The first
option is off the CD that comes with your Lewis & Loftus Java
book. Installing it is simple enough--follow the instructions
for the installer and you should be good to go. Note, however,
that Java is not actually on the CD. Rather, it will come from
the internet, so make sure that your computer has a network
connection when you pop in the CD.
Your second option is to download Java off the Internet manually.
Go to the Java download page
at http://www.oracle.com/technetwork/java/javase/downloads/index.html
and look for the "JDK 7" option. Click
"Download JDK". Choose your platform and language, read through the license agreement and click "Continue". Be sure you are downloading the JDK and not "JRE".
Save the file in a place that you will remember, sit back, and wait!
Once the download is complete, you should navigate through
your file system to whatever folder you actually downloaded
the Java SDK installer into and double-click on the file. You'll
pretty much just follow on the onscreen instructions, and you
can also most likely leave all the values at their defaults.
However, at some point it may ask you about multiple language
support (which is up to you) as well as web browser support.
Whatever web browser you use, make sure you check its box, as
this will allow that browser to view applets.
Congratulations! You've installed Java. Now to configure
it!
Java Installation Overview - Macintosh
WE ARE UPDATING THIS SECTION PRESENTLY.
If you are running Leopard
(Mac OS X 10.5.x), Snow Leopard
(Mac OS X 10.6.x), or Lion
(Mac OS X 10.7.x), you likely
have Java on your machine,
as it probably came with that
on it. But it may be version
5 or 6. If it is 5, we would
like you to upgrade to 6.
Note: On the Mac,
there is an application that
you run to select which of
the downloaded versions of
java you will actually be
using. It is in the
Utilities part of your
Applications menu and is
under Java. It is "Java
Preferences".
Now that Java is installed, we will configure it!
Configuring the Java Virtual Machine - Windows
Now we need to set up the path environment variables
so you can compile and run your programs from the command
line.
Want to
do all of this automatically?
Then run
this program
to automatically configure your paths for the JVM, and none
of the other steps for this section are required!
This section isn't so much
about configuring the VM itself, as
it is setting up Windows to recognize exactly where the VM
is. First, locate the Java
installation on your
computer. Open up My Computer,
then (assuming you installed
it in the default location)
navigate to C:\Program
Files\Java. You should see one
more more folders; find the
one starting with "jdk" with
the highest number (it's
possibly jdk1.7.0_1). Open
that folder, then find the bin
folder inside. Open the bin
folder and look for a program
called "javac.exe". If you see
the program, you've found the
correct folder. The full path
should be something similar to
C:\Program
Files\Java\jdk1.7.0_1\bin.
Copy your path to your
clipboard or memorize it. Now,
you must once again access the
Control
Panel:
1) Click on "My Computer." |
2) On the left side near the middle of the panel,
click "Control Panel." |
Again, if the next window that comes up says "Pick a Category"
across the top, click the "Switch to Classic View" option to
the right of it.
Now, click on the "System" icon. This should bring up a tabbed
"System Properties" window. Click on the
"Advanced" tab.
Near the bottom of the window will be a button with the
title "Environment Variables"
From the list of variables on the bottom, highlight the one that says "PATH"
Click the "Edit" button, then in the "Variable Value"
field, put a semicolon ( ; ) at the end of whatever is
already there, and then type or paste the Java path you found earlier. Again, it should be similar to:
C:\Program Files\Java\jdk1.7.0_01\bin
(Note: if you did not install the latest JDK from Sun's website,
the path will NOT be the same as above. In this situation,
please use the automated program listed above to set up your
environment variables or go to your Program Files\Java folder and look for the most recent jdk as mentioned above)
Click ok, close any command prompts you might have open, and your system should be able to find the Java VM after you open a new command prompt. You can test by opening a command prompt and typing "javac"...if it says "not recognized as an internal or external command", it isn't working yet. If it doesn't work immediately, be sure all command prompts are closed and try again. If that doesn't work, try rebooting (it usually works without rebooting though).
Configuring the Java Virtual Machine - Macintosh
If you have Java 6 on
your machine, it is likely
configured correctly to be used.
If you aren't able to run java
from the command line, you
likely need to add /usr/bin to
your path. Consult the
documentation for your command
shell in case you do not know
how to modify your command
path.
Overview and Installation of IDEs - Windows
As mentioned earlier, IDE is short for Integrated Development
Environment. Essentially, this means it's a nice and pretty
and easy-to-use interface in order to write all your code and
subsequently run, test, and debug your programs. You could,
technically, develop all your code without an IDE. However,
an IDE can greatly simplify many tasks, and for the purposes
of this class, making it that hard on yourself won't help you
in the least. Here is a quick summary of the more well-known
IDEs out there.
An important note to remember: If you have never used an
IDE before (examples listed in bold below), we strongly
recommend using the IDE provided on the CD you can find in your
book: JGrasp. Find its description in the list of IDEs below
for information on where to find JGrasp if you do not have a
copy of the CD in the book. Note that almost all the other IDEs
have some quirks which make them tricky to use on our HW assignments,
unless you really know what you are doing. Use them at your
own risk!
JGrasp
JGrasp is a relatively simple IDE to use and has been designed
to help out new java programmers. It comes with a built-in debugger,
which you may find valuable a little later in the course.
This will be the IDE this tutorial focuses on. This is also
the IDE that CS 1331 officially supports. It can be found for
download on the JGrasp website,
but you can also install it directly off the CD that comes with
your Java book. If you are a CS major, you might want
to look into an IDE with a little more power, at least for future
use. For the purposes of this class, this IDE and any others
listed here will do just fine.
Eclipse
Probably the favorite among hardcore CS majors at Georgia Tech
(ask any CS 2335 student), Eclipse is the ultimate in both power
and configurability, sporting syntax and coding style correction
plug-ins, graphical GUI editors, automatic code and javadoc
completion functions, and dozens more with its extensive plug-in
library. Its only downside is its learning curve, and its programming
power far exceeds what you will need for this course. However,
if you plan on taking more CS courses down the road, it is something
you may at least want to have a look at eventually. It is available
for free download off the Eclipse
website.
NetBeans
This is the IDE which Sun offers in one of its downloads, packaged
with the Java Software Development Kit. It is a significant
step above JGrasp in terms of both learning curve and programming
power, and also sports a graphical GUI builder, which can make
GUI assignments much easier to accomplish. You can download
NetBeans either from the Sun website,
or from the NetBeans website.
JCreator
This is sometimes the favorite for some middle-of-the-road programmers.
It is quite easy to use, has a very friendly interface, and
has a free version that can be downloaded off the internet from
the JCreator webpage.
This IDE will satisfy the majority of programmers out there,
from the beginners all the way up to most recreational programmers
("Wait, you mean people program for fun?..."). For most
upper-end and corporate developers, however, it becomes relatively
underpowered.
JBuilder
This IDE is along the same lines as NetBeans and is also available
on numerous platforms. It boasts syntax-correcting help functions,
easy plug-in capabilities with 3rd party Java packages, and
some powerful project management capabilities. For the average
programmer, this may be more than is needed, plus its learning
curve is a tad steep. However, this will satisfy most high-end
and corporate programmers. JBuilder can be downloaded off the
JBuilder website. You may need to register to download JBuilder.
As an interesting side note, it is worth mentioning that
it is entirely possible to write your Java files in plain text
editors like Windows Notepad. Additionally, if you are of the
more ambitious type, famed text editors like Emacs or vi (in
which this help file was written!) can be used as well to generate
your source code. In fact, many students prefer actually typing
in code initially through some text editor such as Notepad,
emacs, or vi and then opening that file in JGrasp. (But make
sure not to use Word!) Once your source text file has been opened
in an IDE, it can be edited in whatever ways you wish, compiled,
and run.
Writing a Java Class - Windows
Alright! You're in the home stretch for setting up Java and
getting your first application off the ground. Bear with me
for just a little longer - you're already well beyond the hardest
parts (unless I screwed up somewhere and something isn't working
quite right, in which case you should contact your TA or instructor!).
From the "File" menu, create a New Java file. This should
instantly create a new text file in the large blank space of
your JGrasp window. Type these mysterious words into this text
window:
public class Test {
public static void main(String [] args) {
System.out.println("Hello!");
}
}
|
My my, this sure looks mysterious! Let's see what this code
means, exactly. The first part:
public class Test {
This is a declaration. It is creating a class called "Test."
A class, in Java, is more accurately known as an Object. Think
about Object intuitively, as you would any actual tangible,
physical object that does...something. A car, for instance,
could be an Object. All Object have attributes, or the
specific aspects of the Object that make it what it is. For
a car, its attributes could be tires, seats, power locks, XM
radio, a turbocharged V6, a 6-disc changer...you get the idea.
Objects will also have member methods, or the functions
that cause the Object's attributes to interact together, or
even with other Objects, to accomplish certain tasks. For instance,
with the assistance of roads and signals, and utilizing its
power steering, tires, and engine, a car can "drive."
For this example, we're keeping it simple. This class, or
Object, will not do anything other than print out some sentences.
An important thing to note, first. Java is picky about syntax.
Whatever you name the .java file (the file in which you will
write your programs), that must also be the name of the class
itself (the word after "public class ____"), and it
is case-sensitive.
Now back to our original text window. You should have typed
in the original example, and now you should save it. Go to "File"
and select "Save As." Type in "Test.java" and save wherever
you feel appropriate (as a good rule of thumb, save all your
.java files for a single project in the same folder). Now, your
window should look something like this:
Now that you have the class name and file name matching correct,
let's continue with our analysis of this short block of code.
The next part:
public static void main(String [] args) {
Without going into too much detail about the meanings of
each individual word there, just know that every project
you write will need to have at least one of these in
it. When you run the project, this is what Java will look for
at the very beginning, and execution of your entire project
will start here. Next line:
System.out.println("Hello!");
Here, an Object is being used! It is an Object called "System,"
and we are using one of its member methods to do something.
In this case, the method is called "println" and it prints out
to your monitor whatever is written inside the quotation marks
that are inside the parenthesis.
Remember, Java is very picky about syntax, so every curly
brace you open, you must close. Every opening parenthesis must
be matched by a closing parenthesis. Also, you need semicolons
at the end of every line of execution code (as shown in the
example).
Now the moment of truth! Let's see if this sucker runs and
does what it should. From the "Compiler" menu, choose "Compile."
The rectangle at the very bottom of the screen should now be
displaying some bizarre commands as the Java compiler and Virtual
Machine go to work. Should everything behave properly, you should
eventually see a "process completed" output appear, signaling
that compilation went fine and your Object is now ready for
execution. From the "Run" menu, select "Run," and you should
see everything inside the println( ) parenthesis print
out into the rectangle! Experiment and change what is inside
those parenthesis, recompile the file, and run it again.
Writing a Java Class - Macintosh
Interestingly enough, there are no differences between
writing a class / Object in Windows as opposed to Macintosh,
as both use the same JGrasp IDE to do so. The only difference
comes in at the command line compilation and execution. For
the purposes of easy reading, all pertinant information about
writing a class, compiling it, and running it in JGrasp will
be copied here.
Alright! You're in the home stretch for setting up Java and
getting your first application off the ground. Bear with me
for just a little longer - you're already well beyond the hardest
parts (unless I screwed up somewhere and something isn't working
quite right, in which case you should contact your TA or instructor!).
From the "File" menu, create a New Java file. This should
instantly create a new text file in the large blank space of
your JGrasp window. Type these mysterious words into this text
window:
public class Test {
public static void main(String [] args) {
System.out.println("Hello!");
}
}
|
My my, this sure looks mysterious! Let's see what this code
means, exactly. The first part:
public class Test {
This is a declaration. It is creating a class called "Test."
A class, in Java, is more accurately known as an Object. Think
about Object intuitively, as you would any actual tangible,
physical object that does...something. A car, for instance,
could be an Object. All Object have attributes, or the
specific aspects of the Object that make it what it is. For
a car, its attributes could be tires, seats, power locks, XM
radio, a turbocharged V6, a 6-disc changer...you get the idea.
Objects will also have member methods, or the functions
that cause the Object's attributes to interact together, or
even with other Objects, to accomplish certain tasks. For instance,
with the assistance of roads and signals, and utilizing its
power steering, tires, and engine, a car can "drive."
For this example, we're keeping it simple. This class, or
Object, will not do anything other than print out some sentences.
An important thing to note, first. Java is picky about syntax.
Whatever you name the .java file (the file in which you will
write your programs), that must also be the name of the class
itself (the word after "public class ____"), and it
is case-sensitive.
Now back to our original text window. You should have typed
in the original example, and now you should save it. Go to "File"
and select "Save As." Type in "Test.java" and save wherever
you feel appropriate (as a good rule of thumb, save all your
.java files for a single project in the same folder). Now, your
window should look something like this:
Now that you have the class name and file name matching correct,
let's continue with our analysis of this short block of code.
The next part:
public static void main(String [] args) {
Without going into too much detail about the meanings of
each individual word there, just know that every project
you write will need to have at least one of these in
it. When you run the project, this is what Java will look for
at the very beginning, and execution of your entire project
will start here. Next line:
System.out.println("Hello!");
Here, an Object is being used! It is an Object called "System,"
and we are using one of its member methods to do something.
In this case, the method is called "println" and it prints out
to your monitor whatever is written inside the quotation marks
that are inside the parenthesis.
Remember, Java is very picky about syntax, so every curly
brace you open, you must close. Every opening paren must be
matched by a closing paren. Also, you need semicolons at the
end of every line of execution code (as shown in the example).
Now the moment of truth! Let's see if this sucker runs and
does what it should. From the "Compiler" menu, choose "Compile."
The rectangle at the very bottom of the screen should now be
displaying some bizarre commands as the Java compiler and Virtual
Machine go to work. Should everything behave properly, you should
eventually see a "process completed" output appear, signaling
that compilation went fine and your Object is now ready for
execution. From the "Run" menu, select "Run," and you should
see everything inside the println( ) parenthesis print
out into the rectangle! Experiment and change what is inside
those parenthesis, recompile the file, and run it again.
Compiling and Running Java programs from the command prompt
It is important to know how to compile and run your code
from the command line, as this is how the TA's will be grading
all of your work. Before submitting your homework, it
is highly recommended that you verify that your code compiles
and runs from the command line.
Using Windows:
To open up a command prompt, click the your "Start" button,
and then click "Run." Type "cmd" and hit Enter, and a
new window should pop up that is black and has some gray depressing
text on it. You will need to navigate to the directory where
you saved your .java files.
Type the command as you see it there, except replace everything
after the backslash ( \ ) with the path to wherever you saved
your .java files.
To compile the files, enter:
javac
JavaClassNameHere.java
Where "JavaClassNameHere" is
the name if your Java program. If you want to compile
all the files in the current directory, enter:
javac
*.java
To then run the compiled code,
enter:
java -cp . JavaClassNameHere
(for the example Test.java class specified above, the command
to run would be "java -cp . Test")
The "-cp ." parameter specifies
the "class path", which is the directory that any required class
files are read from
(If your confused about what this means, don't worry, as its
not important to understand right now. But just remember
to use the javac command as specified above.)
Notice that you must specify the .java extension when you
compile, but not when you run the code.
Using a Mac:
The procedure for compiling and executing java code from
a command prompt is the same for all operating
systems, in that the syntax for using java and javac are identical
for Windows, Mac, and Unix (Linux) systems.
Refer to the Compiling and running under windows above,
only use the "terminal" or "shell" to access a command
prompt
Conclusion
Congratulations! You have successfully learned about, downloaded,
installed, and configured the Java Virtual Machine and software
development kit, as well as tied a fully-functional IDE in with
it to ultimately produce a working Java application! Not to
mention, you can now look like an erudite programming guru by
compiling and running your source files from the command prompt.
This tutorial was meant to give some insight into getting
an introductory Java course off the ground, especially to those
have had little or no previous programming experience. I have
almost always found the most difficult part of the course
not to be the homeworks or exams or quizzes, but rather
setting up everything that I need to complete all those assignments,
and unfortunately, it is this "setting up" information that
seems the hardest to come by. To those in the same boat as I,
this is for you. Remember that there are also countless other
useful IDEs out there aside from the ones mentioned here.
I hope you have found this introduction to be useful. As
you become more comfortable in the Java programming environment,
you will find most IDEs to be friendly in terms of their flexibility
with your goals for your programs. As a disclaimer, if you are
having ANY problems doing anything mentioned in this
tutorial, do not be hesitant to ask any of your TAs, professors,
or even fellow students for clarification, as getting all this
basic functionality to work is crucial to successfully
completing CS 1331. Even a week of dealing with dysfunctional
classpaths and sick Virtual Machines can set your integration
into CS 1331 back several weeks.
Good luck and good programming!
|