Sei sulla pagina 1di 28

Introduction

What is programming?
This book is all about how to learn to program using the Java
programming language, but many of you may be wondering what you are
getting into. You may have heard statements like these about
programming:

“There is a high demand for programmers in the marketplace”


“Programming is too complex”
“Programming is fun”
“Programming looks boring”
“Programmers are paid really well”

Computers are everywhere in our lives today and it is the software


programs that make those functional for us. Imagine the world without
your smart phone, your tablet, your laptop, the Internet, and all sorts of
other devices like your car, television, and medical devices that have
computers built into them. Programmers create all the software that brings
these devices to life. As long as there is a demand for all of this
technology, there will be a need for programmers, and they will continue to
be paid well for their skills.

The applications and programs that run on these devices do amazing


things to make our lives better and somehow seem somewhat magical. By
their very nature, programs are complex but so are many of the other
wonderful things in our lives. Consider the wonder of how all of the
intricate parts of a building, a car, a plane, an organization, a symphony,
or a novel come together in a beautiful way to better our lives. All of these
wonders are accomplished by a group of people working together over a
period of time. They break down the complexity into a set of smaller parts
that can be solved easily and brought back together into a meaningful

© 2015 R. Kent Jackson 1


whole. It takes creativity, good communication and hard work to
accomplish this. So it is with programming.

It takes time, practice and experience to become a good programmer just


as it takes time, practice and experience to become a good artist,
engineer, builder or musician. There will be many new concepts, skills and
even a new programming language introduced in this book. You may feel
at times that you do not have a total grasp and understanding of
everything right away. Do not let this frustrate you. Continued practice will
improve your skills and understanding, and before long you too will be
creating programs that do amazing things too.

The Java Programming Language


Computers have come along way but they do not yet fully understand our
speech so special programming languages were developed that contain
commands that the computer can clearly understand. These languages
have very precise rules and have a limited vocabulary. These language
rules are referred to as the syntax of the language.

The programming language you will be learning in this book is Java. Select
the link below to view the video to learn more about the Java programming
language. After watching each video you will need to hit the Back button
in your browser to return back to this document.

Introduction to the Java

© 2015 R. Kent Jackson 2


Object Oriented Concepts
Java is an object oriented programming language. To learn more about
object oriented programming concepts watch the video below. After
watching each video you will need to hit the Back button in your browser
to return back to this document:

Object Oriented Concepts video

Here is a list of object oriented concepts that you need to learn know:

Object: A program is made up of one or more objects. Objects are the


persons, places or things that need to be modeled in the
program. Objects are always nouns, and they must represent
something that is important in the system being creating.

Class: A class describes a group of objects that are all of the same
type. A class defines: 1) the attributes or important
characteristics that need to be remembered for each object of
the class, and 2) the functions that the objects of this class
can perform. A class serves as blueprint for defining and
creating objects that are all of the same type.

Attributes: The attributes in a class describe the data items that


associated with each object of this type. A variable is defined
in the class for each attribute. Each attribute defined in the
class must be logically related to the theme or purpose of the
class.

Functions: The functions in a class define the behavior of the objects in


the class. A function is an executable block of code that
performs some task. Each function in the class must be
logically related to the theme or purpose of the class.

Instance: An instance of a class is an actual occurrence of an object of


the class. A class is a definition of a group of objects of of the

© 2015 R. Kent Jackson 3


same type. Instances are the actual objects created from the
class type definition.

The structure of a Java Program


A Java program is made up of a group of source files. Each source file
contains the definition of a single class.

The file name of each of source file must be the same as the name of the
class and end with the file extension .java. For example, the name of the
source file for the PlayingPiece class is PlayingPiece.java.

One of the class files in the program must always contain a function
called, main(). The main() function tells the computer where to start
executing your program. The computer looks for the class that contains
the main() function and then starts execution of the program at the first
statement in that function. The main() function is usually placed in the
class that represents the program itself.

Lets assume that we are creating a program for a checkers game. We


would first create a source file to define the Checkers class. This class
models the checkers game and this is where we want the computer to
start execution so we will add the main()function to the Checkers class.
We would also create several other source files for the program to define

© 2015 R. Kent Jackson 4


the Player, PlayingPiece, and Board classes, but only the Checkers
class should have a main()function.

The anatomy of a java source file


Lets take a closer look at another java source file for the PlayingPiece
class to help us get a better understanding of a java class file. 5

© 2015 R. Kent Jackson 5


At the top of source file is a package statement and a list of import
statements. The package statement identifies the package that this source
file belongs to. Packages logically associate a group of source files
together. The import statements identify other classes being used or
referenced in this source file. There are two import statements for the
Dimension and Player classes being used or referenced in this class.
The class statement always follows the import statements. This statement
defines the beginning of a class and the name of the class.

The block of code after the class statement defines the attributes and
functions of the class.

Begins block

Indent
Block

Ends block

A block in Java starts with a left curly brace{and ends with a right curly
brace }. A block defines a group statements that are logically related
together.

© 2015 R. Kent Jackson 6


Class instance variables variables are defined at the top of the block by
convention for each of the attributes defined in the UML class diagram.

Class instance variables

They are called class instance variables because the variables


individually belong to each object instance.

Unique memory locations are assigned to each of the variables for each
object instance when an object is created. This is illustrated in the two
PlayingPiece object instances below. Each of the class instance

© 2015 R. Kent Jackson 7


variables has it’s own memory (represented by the yellow boxes) with
different values assigned to the variables for each object instance.

The class functions typically follow the class instance variables (attributes).
There move() and attack() functions are defined in the PlayingPiece
class below.

Class functions

© 2015 R. Kent Jackson 8


Each function starts with a function signature that specifies how the
function is to be used. It starts with one or more modifiers that define the
visibility and how the function is to be called. This is followed by type of
value to be returned from the function, the name of the function, and the
list of input parameters enclosed within parenthesis.

Return Function Parameter


Visibility type name list

Function
signature

The block of statements to be executed for the function are enclosed


within curly braces and are normally indented for readability.

Indent
Block

Ends block

© 2015 R. Kent Jackson 9


Blocks of statements can be nested inside each other.

Indent

Indent

In the example, a block associated with the if statement is nested within


the block belonging to the attack() function which is nested within the
block associated defining the PlayingPiece class. Notice that all of the
statements within each of the blocks is indented. This improves readability
and makes it easier to find errors when you forget or put a curly brace in
the wrong place.

© 2015 R. Kent Jackson 10


Basic rules of the language
Before we start developing our first Java programming there are some
basic rules of the Java language that you need to be aware of.

Case sensitive
Java is case sensitive. This means that it recognizes the difference
between upper and lower case letters. For example, it distinguishes the
difference between the words, price, and Price.

Free-form
Writing a Java statement is very similar to writing a sentence in english.
They can start anywhere in a line and can flow from one line to another.
White space (blanks) is used to distinguish one token in a statement from
another. In english, a sentence must end with either a period, exclamation
or a question mark. In Java, every statement must end with either a
semicolon (;) or a right curly brace (}) .

Naming Java Identifiers


An identifier is a name given to a variable, a function, a class, or a constant
in Java. The rules and conventions for naming identifiers is very similar to
those used in C, C++ and C#.

Case sensitive
Java is case sensitive. This means that it recognizes the difference
between upper and lower case letters. For example, it distinguishes the
difference between the words time, Time, TIME, timE, and tImE.

Rules for naming identifiers


All identifiers in Java must abide by the following rules.

• Can only contain lower and upper case letters (a-z, A-Z), numbers
(0-9), and the special characters, dollar sign and underscore. No other
characters are allowed,

© 2015 R. Kent Jackson 11


• Can not start with a number,

• Can not contain any blanks.

Here are some examples of valid identifiers:

Player, currentTime, customer25, the_total, FRIDAY,


$Year

Here are some examples of invalid identifiers:

tom&jerry, rate*time, 14thday, day of week

The names tom&jerry and rate*time are invalid because they contain
the illegal characters & and * respectively. The name 14thday is illegal
because it starts with a number. The name day of week is illegal
because it contains blanks.

Meaningful names
You should use mnemonic names for identifiers.This means that the
names should be descriptive of what they are representing. Sometimes
this requires that we combine multiple words together; however, Java does
not allow blanks in an identifier.

Camel Case
One of the rules for identifier names is that they can not contain blanks. To
overcome this restriction a common convention called “camel case” is
used by most Java programmers to create meaningful identifiers that
contain multiple words. This is done by stringing the words together
without blanks and capitalizing the first letter of each word after the first
word (e.g., currentRetailPrice,timeOfDay,totalWeight,etc).

© 2015 R. Kent Jackson 12


Reserved words
Certain words are reserved in the Java and can not be used for an
identifier. All of these words are used as part of the syntax of Java
language statements.

abstract continue for new switch


assert default goto package synchronize
boolean do if private this
d
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while

Naming conventions
Java programmers follow specific conventions when naming variables,
functions, classes, and constants. This allows those reading the code to
immediately identify what type of identifier the name is referring to.

Identifier Conventions Examples

Variables names should always start with a lowercase price


alphabetic letter and be meaningful in camelCase form. totalTime
The use of the underscore ( _ ) or a dollar sign ( $ ) at grade
midTermScore
the beginning of the name should be avoided even
Variable
though is valid to do so. One character names are
generally not used except for temporary variables. For
example, using the names i and j for counter variables
in a loop.
Function names should also start with a lowercase getScore()
alphabetic letter and be meaningful in camelCase form. deleteItem()
The name are generally verbs or verb phrases indicative calcTotal()
Function of the task that they perform. The identifier is always display()
followed by parenthesis. The parenthesis are used to
indicate to the compiler and the programmer that the
identifier is referring to a function.

© 2015 R. Kent Jackson 13


Identifier Conventions Examples

Class names should start with an uppercase letter and Item


be meaningful and in camelCase form. The name are PurchaseOrder
Class Customer

generally noun or noun phrases representing a person,


place or thing.
A constant is a variable whose value never changes. CLASS_SIZE
Constants names should be in all uppercase letters. MAX_WEIGHT
Constant Underscores ( _ ) are used between words instead of TAX_RATE
the camelCase format when the name is made up of
more than one word.

Literals
There are times when you want the computer to treat what you type as a
literal value and not be interpreted as an identifier or a keyword in a
command. The way you do this is different for numbers, individual
characters and a text string.

Integer Floating Point Character String

125 3.14 ‘A’ “Java is fun”

Integer and floating point (decimal numbers) are typed as regular numbers.
Never use a currency symbol (e.g., $) or commas in a literal number.
Individual characters must be surrounded by single quotes ('B'). Text
strings can must be surrounded by double quotes ("Hello world!").

Comments
It is a good programming practice to document your code by adding
comments. This makes your code easier to read by others and is
particularly useful when you have to make changes to your code after you
have not seen it for significant period of time. There are three different
types of comments.

© 2015 R. Kent Jackson 14


Single line Used to comment a single line or part of a line. The
comment starts with a // and runs to the end of the
line.

Block Used for a comment where the text will flow over
multiple lines. The comment start with /* and ends with
*/.

Documentation Used by the JavaDoc documentation generator to


generate API documentation for the class in an HTML
format. The comment must start with /** and ends
with */. The comment may contain HTML tags and
documentation annotations that start with the @ symbol.

All three types of comments are illustrated in the example below.

Block comment

Documentation
comment

Line comment

We used a block comment at the top of the file to give a general


description of the class. We used a documentation comment to describe
the function. The first line of the documentation comment contains the
HTML bold tag (<b>) and describes the purpose of the function. The next
line contains the @param annotation to describe the args parameter of
the function. The line comment at the bottom is used to describe what the
statement below is doing.


© 2015 R. Kent Jackson 15


Download and configure Java
You will need to download the Java Development Kit (JDK) and configure
your system to use Java before you can start developing Java programs.

Installing the JDK


The JDK contains the commands and default classes needed to develop
Java programs.

1. Start by download the latest Java Development Kit from the Internet at:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

2. Select the button to download the JDK. Accept the License Agreement
and then select the download file associated with the version of the
operating system that you are using.

3. Once the file is downloaded, locate the file and double click on the file
to install the JDK on your machine. Take all of the defaults during the
installation process.

Modify the search path


It is highly recommended that you add the JDK bin directory to the default
search path for your operating system. This will allow you to type in the
java commands (javac, java, etc.) without having to enter the fully qualified
path to the bin directory each time you run a Java command. The default
search path is defined in an environment variable called PATH. Follow the
instructions for your operating system below.

Microsoft Windows
1. Locate and find file path of the JDK bin directory using File Explorer.
Normally, this will be found under the C:\Program Files\Java directory
and look similar to this except that the version number (e.g..
jdk1.8.0_91) may be different.

C:\Program Files\Java\jdk1.8.0_91\bin

© 2015 R. Kent Jackson 16


2. Start the Control Panel program and select System and Security,
then System.

3. Select the Advanced system settings and then Environment


Variables.

4. Scroll down and select the Path environment variable under the
System Variables section and then select the Edit button.

5. Type a semicolon at the end of the value and then type the fully
qualified path of the JDK bin directory as illustrated in the example
below.

C:\WINDOWS\system32;C:\WINDOWS;C:\Program
Files\Java\jdk1.8.0_91\bin

6. Then select the OK button

Mac
1. Locate and find the file path of the JDK bin directory in the Finder
program. Normally, this will be in the following folder except that the
value of the version number (e.g., jdk1.8.0_91.jdk) may be
different.

/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/
Contents/Home/bin

2. Edit the .bash_profile file in your home directory. Open the


terminal program and enter the following command to edit the file.

vi ./.bash_profile

3. Use the arrow keys to move down to the bottom of the file and then
type the letter ‘O’. This put you into insert mode.

4. Type the following command on one line. Use the fully qualified path
of the JDK bin directory you located in step 1.

© 2015 R. Kent Jackson 17


export PATH=$PATH:/Library/Java/JavaVirtualMachines/
jdk1.8.0_91.jdk/Contents/Home/bin

5. Press the esc key and type the colon key ‘:’ and. This puts you into
command mode.

6. Save and quit the file by typing “wq” on the command line at the
bottom of the screen and pressing Enter.

The basic steps of developing a Java program


The steps for developing a program are:

1. Create the source files to define the class for your program. The source
file is always the same name as the class and is saved with a file
extension of .java.

2. Compile the source files. The compiler is a program that checks the
syntax of all of the statements in a source file. It makes sure that none
of rules of the language language have been violated (e.g., missing curly
brace, a word is misspelled, etc.). It is very similar to running a grammar
checker in a word processing program. The compiler then translates the
code from Java into a machine language called bytecodes if there are
no syntax errors, and creates a file with the same name as the class
followed by the file extension .class.

3. Run the program. Execute the bytecodes .class file with the main()
function in the Java Virtual Machine (JVM).

© 2015 R. Kent Jackson 18


If the program does not work as anticipated, you will need to repeat the
process of modifying the source file, re-compiling, and running to testing
the program until it works correctly.

Text Editor
You will need a text editor to create the source files for the Java classes in
your program. There are some very good text editors that you can
download and install for free from the Internet. Search the Internet using
the keywords “text editors for Windows” or “text editors for mac” to find a
list of text editors that you can download. Two good free open source
editors are Notepad++ for Microsoft Windows and TextWrangle for Mac.
Both Windows and Mac systems also ship a very rudimentary text editors
programs if you do not want to download one from the Internet. (i.e.,
NotePad on windows, TextEdit on mac).

Warning: Do not use a Word Processor (e.g., Microsoft Word)


program to create and edit your source files because they

© 2015 R. Kent Jackson 19


Your First Java Program
There is no better way to learn than by doing. Let’s start by creating a
simple java program that will convert the weigh of an item from pounds to
kilograms. The program will contain only one class called
ConvertWeight with main()function.

Here is a basic outline of the instructions in the main()function.

a. Print a welcome message describing the purpose of the program.

b. Prompt the user to enter their name.

c. Get the name and save it in a variable for later user.

d. Prompt the user to enter a weight in pounds.

e. Convert the weight to kilograms.

f. Print out a personalized message showing the weight in kilograms.

A good programming practice to follow is to develop a program step by


step. Write some code and test it, and then write a little bit more code and
test it. Continue this process until you have written entire program. This
makes it much simpler to debug and figure out where problems are
occurring. If an error occurs, it is most likely in the last set of instructions
added. This helps isolate the problem to those few lines of code.

Lets start by creating the source file for the ConvertWeight class and
add a main() function to it. The main() function will initially have only
one statement to print out the welcome message. We will then compile
and run the program to test to see if it works correctly. The remaining
functionality will be added later.

© 2015 R. Kent Jackson 20


Step 1 - Create the source file.

1. Open a text editor and type in the following statements.

It is important that you understand what each statement you typed


before moving on. Select the link below to view a video clip that gives a
detailed explanation of the program.

Description of the ConvertWeight program part 1

2. Save the file with the name ConvertWeight.java.

Step 2 - Compile the source file


Compile the source file to check for syntax errors and to translate the
source into Java bytecodes.

1. Open up a command console on your machine. This is done by starting


the Command program if you are using Windows, or the Terminal
program if you are using a Mac or Linux.

© 2015 R. Kent Jackson 21


2. Navigate to the folder where the ConvertWeight.java source file
was saved.

a. First view the contents of the current working directory to see if the
file is in the current working directory

On a Windows system, you enter the dir command to view the


contents of a directory.

>dir
03/20/2015 10:03 AM <DIR> .
03/20/2015 10:03 AM <DIR> ..
03/20/2015 10:15 AM <DIR> Contacts
03/20/2015 10:15 AM <DIR> Desktop
03/20/2015 10:17 AM <DIR> Documents
03/20/2015 10:18 AM <DIR> Downloads
03/20/2015 10:19 AM <DIR> Links
03/20/2015 10:20 AM <DIR> Music
03/20/2015 10:21 AM <DIR> Pictures
03/20/2015 10:22 AM <DIR> Videos

On a Mac or Linux system, use the ls command to view the contents


of the current working directory.

>ls
Applications Library
Desktop Movies
Documents Music
Downloads Pictures

b. If you do not see the file in the current working directory you will
need to using the cd command to navigate down the hierarchy to the
directory (folder) where you saved the ConvertWeight.java file. In
the example below, the file was saved in the Desktop directory so
we typed the following command.

>cd Desktop

© 2015 R. Kent Jackson 22


Use the cd command to navigate to the folder where you saved
your file.

c. Again view the contents of the directory using either the dir
(Windows) or ls (Mac, Linux) command to see if the file is in the
directory you just changed to.

>dir
03/20/2015 10:15 AM <DIR> .
03/20/2015 10:15 AM <DIR> ..
03/22/2015 09:45 PM <DIR> apps
04/22/2015 10:25 AM ConvertWeight.java

If the file is not in the current working directory continue navigating


down the directory hierarchy until you find the directory that you
saved the file in.

3. Once you have located the ConvertyWeight.java file, use the


javac command to compile your program. Type javac command
followed by the full name of source file.

> javac ConvertWeight.java


>

The javac command checks for syntax errors. It then translates the
Java code into bytecodes if there are no errors and saves the result in a
file called ConvertWeight.class. A command prompt is then
displayed indicating that no syntax errors were found in your program.

If your program compiled successfully without errors, list the files in the
current directory using either the dir (Windows) or ls (Mac or Linux)
command to make sure that the ConvertWeight.class file was
created.

© 2015 R. Kent Jackson 23


>dir
03/20/2015 10:15 AM <DIR> .
03/20/2015 10:15 AM <DIR> ..
03/22/2015 09:45 PM <DIR> apps
04/22/2015 10:25 AM ConvertWeight.java
04/22/2015 10:38 AM ConvertWeight.class

An error message will be displayed on the console if there is an error. It


will indicate the line number that the error occurred on and show you
the approximate position in the line where the error occurred as
indicated by the ^ character. You will need to fix the error and recompile
the code until no more errors are found. See the section below for a list
of common syntax errors. An explanation of the cause and a suggestion
on how to fix these error is given for each error. You can also “Google”
the error to find a solution to your program.

Common Java Syntax errors


Here is a list of common errors that often occur when compiling a Java
program.

Error: Can not find the javac command


If you get either of the messages below based on the on the operating
system you using you will need to go back and redo the section on
Modifying the search path.

Windows

'javac' is not recognized as an internal or external


command, operable program or batch file

Mac

javac: Command not found

© 2015 R. Kent Jackson 24


Error: ';' expected
You have forgotten to end one of your statements with a semicolon (;) if
you get a message like this. The line number is listed in the message.

ConvertWeight.java:14: ';' expected

Go to the line number (14) listed in the message. Check the line
specified and/or the previous line for a missing semicolon and then
modify the source code to add a semicolon at the end this statements.

Error: cannot find symbol or undefined symbol


The compiler does not recognize an identifier as illustrated in the
message below.

ConvertWeightErrors.java:16: error: cannot find


symbol

The most common causes of this error is the misspelling of an identifier


or that a variable is not defined. Go to the line number specified and
checking the spelling. Remember that java distinguishes between lower
and and uppercase letters.

Error: reached end of file while parsing


You either have either mismatched curly braces or quotes somewhere
before the specified line number (18) as shown in the example below.

ConvertWeightErrors.java:18: error: reached end of


file while parsing

Start searching backward and make sure that there is a right curly
brace for every left curly brace in the file, and that there is an ending
quote for every beginning quote in the file.

© 2015 R. Kent Jackson 25


Step 3 - Run and test your program
You run a Java program by typing in the java command followed by the
name of the source file of the class that contains the main function. Type
the following command:

> java ConvertWeight

Your program should execute successfully and display the following text in
the console.

> java ConvertWeight

This program converts pounds into kilograms

© 2015 R. Kent Jackson 26


Part B - Implement the rest of the program
Lets modify the ConvertWeight program and implement rest of the
program.

Step 1 - Modify the source file


Open the ConvertWeight.java source file again in a text editor and add
the highlighted lines of codes. Then save the file. 


© 2015 R. Kent Jackson 27


Again, it is important that you understand what each statement you typed
before moving on. Select the link below to view a video clip that gives a
detailed explanation of the program.

Description of the ConvertWeight program part 2

Step 2 - Compile the source file


Open up a console window and type the javac command below to
compile the source file.

javac ConvertWeight.java

Modify your source file and recompile until there are no more syntax
errors.

Step 3 - Run and test your program


Type the following command to run your program

java ConvertWeight

Enter in your name and a weight when prompted.

Your program should execute successfully and display the following in the
console.

This program converts pounds into kilograms


Please enter name:
Fred Flintstone

Enter the weight in pounds:


150

******************************************************************
Fred Flintstone, The weight is 68.0388 kilograms
******************************************************************

© 2015 R. Kent Jackson 28

Potrebbero piacerti anche