Java 4 TOC+Ch1
Java 4 TOC+Ch1
Getting started
Performing operations
Introduction
Installing the JDK
Writing a first Java program
Compiling & running programs
Creating a variable
Recognizing data types
Creating constants
Adding comments
Troubleshooting problems
Summary
Doing arithmetic
Assigning values
Comparing values
Assessing logic
Examining conditions
Setting precedence
Escaping literals
Working with bits
Summary
Making statements
Branching with if
Branching alternatives
Switching branches
Looping for
Looping while true
Doing do-while loops
Breaking out of loops
Returning control
Summary
7
8
10
12
14
16
18
20
21
22
24
25
26
28
30
32
34
36
38
40
42
43
44
46
48
50
52
54
56
58
60
Directing values
Manipulating data
Creating classes
Importing functions
Handling files
Reading console input
Reading files
Writing files
Sorting array elements
Managing dates
Formatting numbers
Calculating currency
Summary
61
62
64
66
68
70
72
74
76
78
79
80
82
84
86
88
90
92
94
96
97
98
100
102
104
106
108
110
112
114
115
116
118
120
122
124
126
128
130
132
Building interfaces
Recognizing events
Creating a window
Adding push buttons
Adding labels
Adding text fields
Adding item selectors
Adding radio buttons
Changing appearance
Arranging components
Summary
10
Deploying programs
Methods of deployment
Distributing programs
Building archives
Deploying applications
Enabling Web Start
Producing applets
Converting web pages
Deploying applets
Summary
Index
133
134
136
138
140
142
144
146
148
150
151
152
153
154
156
158
160
162
164
166
168
169
170
172
174
176
178
180
182
184
186
187
Foreword
The creation of this book has provided me, Mike McGrath, a welcome opportunity to update
my previous books on Java programming with the latest techniques. All examples I have given
in this book demonstrate Java features supported by current compilers on both Windows and
Linux operating systems, and the books screenshots illustrate the actual results produced by
compiling and executing the listed code.
Additionally, in order to readily identify each source code file described in the steps a colored
icon and file name appear in the margin alongside the steps, like these:
110100101010
000101101011
110100101010
000101101011
110100101011
JAVA
CLASS
App.java
App.class
JAR
App.jar
JNLP
App.jnlp
l
l
l
1
Find Java in easy steps, 4th Edition in the Source Code list, then click on the
hyperlink entitled All Code Examples to download the archive
Now extract the archive contents to any convenient location on your computer
I sincerely hope you enjoy discovering the programming possibilities of Java and have as much
fun with it as I did in writing this book.
Mike McGrath
Getting started
Introduction
10
12
14
16
Creating a variable
18
20
Creating constants
21
Adding comments
22
Troubleshooting problems
24
Summary
Getting started
Introduction
The Java programming language was first developed in 1990
by an engineer at Sun Microsystems named James Gosling. He
was unhappy using the C++ programming language so he created
a new language that he named Oak, after the oak tree that he
could see from his office window.
As the popularity of the World Wide Web grew, Sun recognized
that Goslings language could be developed for the internet.
Consequently Sun renamed the language Java (simply because
that name sounded cool) and made it freely available in 1995.
Developers around the world quickly adopted this exciting new
language and, because of its modular design, were able to create
new features that could be added to the core language. The most
endearing additional features were retained in subsequent releases
of Java as it developed into the comprehensive version of today.
Compiler
JAVA
Program.java
110100101010
000101101011
110100101010
000101101011
110100101011
Java
VM
CLASS
Program.class
Program
...contd
In order to create Java programs the Java class libraries and the
javac compiler need to be installed on your computer. In order
to run Java programs the Java Runtime Environment ( JRE)
needs to be installed to supply the java interpreter. All of these
components are contained in a freely available package called the
Java Platform, Standard Edition Development Kit ( JDK).
The Java programs in this book use version JDK 7 which,
incorporating both the Development Kit itself and the Runtime
Environment, can be downloaded from the Oracle website at
http://www.oracle.com/technetwork/java/javase/downloads
Getting started
10
l
l
l
l
4
l
5
...contd
The tools to compile and run Java programs are normally operated
from a Command Prompt and are located in the bin sub-directory
of the Java directory. These can be made available from anywhere
on your computer by adding their location to the system path:
Windows 7, Windows Vista, or Windows XP, navigate
On
through Start, Control Panel, System, Advanced System
C:\Program Files\Java\bin;
.bashrc
On older versions of
Windows the JDK tools
can be made globally
available by editing the
autoexec.bat file to add
the location of Javas bin
sub-directory at the end
of the SET PATH line.
11
Getting started
l
1
JAVA
Hello.java
Open a plain text editor, like Notepad, and type this code
exactly as it is listed to create a class named Hello
class Hello
{
12
Java is a case-sensitive
language where Hello
and hello are distinctly
different traditionally
Java program names
should always begin with
an uppercase letter.
l
2
l
l
3
4
...contd
The separate parts of the program code on the opposite page can
be examined individually to understand each part more clearly:
13
The code declares a method named main that will contain the
actual program instructions within its curly brackets.
Keywords public static void precede the method name to define
how the method may be used and are explained in detail later.
The code ( String[] args ) is useful when passing values to the
method and is also fully explained later in this book.
The Statement
System.out.println( Hello World! ) ;
Getting started
l
l
1
14
Open a Command
Prompt/Terminal window
then type javac and hit
Return to reveal the Java
compiler options.
If the javac compiler discovers errors in the code it will halt and
display a helpful report indicating the nature of the error see
page 22 for Troubleshooting Problems.
If the javac compiler does not find any errors it will create a new
file with the program name and the .class file extension.
...contd
When the Java compiler completes compilation the Command
Prompt/Terminal window focus returns to the prompt without
any confirmation message and the program is ready to run.
The Java program interpreter is an application named java that is
located in Javas bin sub-directory alongside the javac compiler.
As this directory was previously added to the system path, on
page 11, the java interpreter can be invoked from any location.
Follow these steps to run the program that was compiled using
the procedure described on the page opposite:
l
l
1
15
The Hello program runs and executes the task defined in the
statement within its main method to output Hello World!.
Upon completion focus returns to the prompt once more.
The process of compiling and running a Java program is typically
combined in sequential steps, and is the same regardless of
platform. The screenshot below illustrates the Hello program being
compiled and run in combined steps on a Linux system:
Getting started
Creating a variable
In Java programming a variable is simply a useful container in
which a value may be stored for subsequent use by the program.
The stored value may be changed (vary) as the program executes
its instructions hence the term variable.
16
Variable names should also avoid the Java keywords, listed in the
table below, as these have special meaning in the Java language.
abstract
default
goto
package
synchronized
assert
do
if
private
this
boolean
double
implements
protected
throw
break
else
import
public
throws
byte
enum
instanceof
return
transient
case
extends
int
short
true
catch
false
interface
static
try
char
final
long
strictfp
void
class
finally
native
String
volatile
const
float
new
super
while
continue
for
null
switch
...contd
As good practice, variables should be named with words or easily
recognizable abbreviations, describing that variables purpose.
For example, button1 or btn1 to describe button number one.
Lowercase letters are preferred for single-word names, such as
gear, and names that consist of multiple words should capitalize
the first letter of each subsequent word, such as gearRatio the
so-called camelCase naming convention.
Once a variable has been declared, it may be assigned an initial
value of the appropriate data type using the equals sign = , either
in the declaration or later on in the program, then its value can be
referenced at any time using the variables name.
Follow these steps to create a program that declares a variable,
which gets initialized in its declaration then changed later:
l
1
l
l
3
4
class FirstVariable
{
public static void main ( String[] args ) {
}
JAVA
FirstVariable.java
If you encounter
problems compiling or
running the program
you can get help
from Troubleshooting
Problems on page 22.
17
Getting started
Data type:
Description:
Example:
char
String
my String
int
1000
float
boolean
true
18
Data type:
Description:
byte
short
long
double
...contd
Follow these steps to create a Java program that creates, initializes,
and outputs variables of all five common data types:
l
1
l
2
JAVA
System.out.println(
System.out.println(
System.out.println(
System.out.println(
System.out.println(
Intial is + letter ) ;
Book is + title ) ;
Days are + number ) ;
Temperature is + decimal ) ;
Answer is + result ) ;
19
l
3
DataTypes.java
Getting started
Creating constants
The final keyword is a modifier that can be used when declaring
variables to prevent any subsequent changes to the values that are
initially assigned to them. This is useful when storing a fixed value
in a program to avoid it becoming altered accidentally.
Variables created to store fixed values in this way are known
as constants and it is convention to name constants with all
uppercase characters to distinguish them from regular variables.
Programs that attempt to change a constant value will not
compile and the javac compiler will generate an error message.
Follow these steps to create a Java program featuring constants:
l
1
JAVA
Constants.java
20
l
l
l
l
td = 4 * TOUCHDOWN ;
pat = 3 * CONVERSION ;
fg = 2 * FIELDGOAL ;
total = ( td + pat + fg ) ;
Adding comments
When programming, in any language, it is good practice to add
comments to program code to explain each particular section.
This makes the code more easily understood by others, and by
yourself when revisiting a piece of code after a period of absence.
In Java programming, comments can be added across multiple
lines between /* and */ comment identifiers, or on a single line
after a // comment identifier. Anything appearing between /* and
*/, or on a line after //, is completely ignored by the javac compiler.
When comments have been added to the Constants.java program,
described opposite, the source code might look like this:
/*
*/
class Constants
{
public static void main( String args[] )
{
// Constant score values.
final int TOUCHDOWN = 6 ;
final int CONVERSION = 1 ;
final int FIELDGOAL = 3 ;
Constants.java
(commented)
21
}
}
//
//
//
//
4x6=24
3x1= 3
2x3= 6
24+3+6=33
Getting started
Troubleshooting problems
Sometimes the javac compiler or java interpreter will complain
about errors so its useful to understand their cause and how
to quickly resolve the problem. In order to demonstrate some
common error reports this code contains some deliberate errors:
JAVA
Test.java
class test
{
public static void main ( String[] args )
{
String text ;
System.out.println( Test + text )
}
}
22
PATH
cannot be found
Cause the file
navigate to the directory where the file is located,
orSolution
use the full path address to the file in the command
Test.java
...contd
23
test
Test
String
= success
Getting started
Summary
.java
.class
program files
PATH
javac
24
main
System.out.println()
char
float
/*
//
*/,