0% found this document useful (0 votes)
4 views22 pages

Chapter1-Introduction To Java Programming

Java, a versatile programming language created in 1995, allows developers to create applications that can run on various platforms, including web servers and mobile devices. It is defined by the Java Language Specification and utilizes the Java Development Kit (JDK) for compiling and executing programs, while Integrated Development Environments (IDEs) like NetBeans and Eclipse facilitate rapid development. Java's syntax and structure are crucial for writing programs, which must adhere to specific rules to avoid syntax errors during compilation.

Uploaded by

nathanaeltchapsi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

Chapter1-Introduction To Java Programming

Java, a versatile programming language created in 1995, allows developers to create applications that can run on various platforms, including web servers and mobile devices. It is defined by the Java Language Specification and utilizes the Java Development Kit (JDK) for compiling and executing programs, while Integrated Development Environments (IDEs) like NetBeans and Eclipse facilitate rapid development. Java's syntax and structure are crucial for writing programs, which must adhere to specific rules to avoid syntax errors during compilation.

Uploaded by

nathanaeltchapsi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

6 The Java Language Specification, API, JDK, JRE, and IDE 33


In 1995, renamed Java, it was redesigned for developing web applications. For the history of
Java, see [Link]/en/javahistory/[Link].
Java has become enormously popular. Its rapid rise and wide acceptance can be traced
to its design characteristics, particularly its promise that you can write a program once
and run it ­anywhere. As stated by its designer, Java is simple, object oriented, distributed,
­interpreted, robust, secure, architecture neutral, portable, high performance, multithreaded,
and dynamic. For the anatomy of Java characteristics, see [Link]/etc/­
[Link].
Java is a full-featured, general-purpose programming language that can be used to develop
robust mission-critical applications. Today, it is employed not only for web programming but
also for developing stand-alone applications across platforms on servers, desktop computers,
and mobile devices. It was used to develop the code to communicate with and control the
robotic rover on Mars. Many companies that once considered Java to be more hype than sub-
stance are now using it to create distributed applications accessed by customers and partners
across the Internet. For every new project being developed today, companies are asking how
they can use Java to make their work easier.
The World Wide Web is an electronic information repository that can be accessed on the
Internet from anywhere in the world. The Internet, the Web’s infrastructure, has been around
for more than 40 years. The colorful World Wide Web and sophisticated web browsers are the
major reason for the Internet’s popularity.
Java initially became attractive because Java programs can run from a web browser. Such
programs are called applets. Today applets are no longer allowed to run from a Web browser
in the latest version of Java due to security issues. Java, however, is now very popular for
developing applications on web servers. These applications process data, perform computa-
tions, and generate dynamic webpages. Many commercial Websites are developed using Java
on the backend.
Java is a versatile programming language: You can use it to develop applications for desktop
computers, servers, and small handheld devices. The software for Android cell phones is
developed using Java.

1.5.1 Who invented Java? Which company owns Java now? Check
Point
1.5.2 What is a Java applet?
1.5.3 What programming language does Android use?

1.6 The Java Language Specification, API, JDK,


JRE, and IDE
Java syntax is defined in the Java language specification, and the Java library is
defined in the Java application program interface (API). The JDK is the software for
compiling and running Java programs. An IDE is an integrated development environ- Key
Point
ment for rapidly developing programs.
Computer languages have strict rules of usage. If you do not follow the rules when writing a
program, the computer will not be able to understand it. The Java language specification and
the Java API define the Java standards.
The Java language specification is a technical definition of the Java programming Java language specification
­language’s syntax and semantics. You can find the complete Java language specification at
[Link]/javase/specs/.
The application program interface (API), also known as library, contains predefined classes API
and interfaces for developing Java programs. The API is still expanding. You can view and library
download the latest version of the Java API at [Link]/jdk8/docs/api/.
34 Chapter 1   Introduction to Computers, Programs, and Java™
Java is a full-fledged and powerful language that can be used in many ways. It comes in
three editions:
Java SE, EE, and ME ■■ Java Standard Edition (Java SE) to develop client-side applications. The applications
can run on desktop.
■■ Java Enterprise Edition (Java EE) to develop server-side applications, such as Java
servlets, JavaServer Pages (JSP), and JavaServer Faces (JSF).
■■ Java Micro Edition (Java ME) to develop applications for mobile devices, such as
cell phones.
This book uses Java SE to introduce Java programming. Java SE is the foundation upon which
Java Development all other Java technology is based. There are many versions of Java SE. The latest, Java SE 8, is
Toolkit (JDK) used in this book. Oracle releases each version with a Java Development Toolkit (JDK). For Java
JDK 1.8 = JDK 8 SE 8, the Java Development Toolkit is called JDK 1.8 (also known as Java 8 or JDK 8).
The JDK consists of a set of separate programs, each invoked from a command line, for
compiling, running, and testing Java programs. The program for running Java programs is
Java Runtime Environment known as JRE (Java Runtime Environment). Instead of using the JDK, you can use a Java
(JRE) development tool (e.g., NetBeans, Eclipse, and TextPad)—software that provides an integrated
Integrated development development environment (IDE) for developing Java programs quickly. Editing, compiling,
environment building, debugging, and online help are integrated in one graphical user interface. You simply
enter source code in one window or open an existing file in a window, and then click a button
or menu item or press a function key to compile and run the program.

Check 1.6.1 What is the Java language specification?


Point 1.6.2 What does JDK stand for? What does JRE stand for?
1.6.3 What does IDE stand for?
1.6.4 Are tools like NetBeans and Eclipse different languages from Java, or are they dia-
lects or extensions of Java?

1.7 A Simple Java Program


A Java program is executed from the main method in the class.
Key
Point Let’s begin with a simple Java program that displays the message Welcome to Java! on the
console. (The word console is an old computer term that refers to the text entry and display
what is a console?
console input
device of a computer. Console input means to receive input from the keyboard, and console
console output
output means to display output on the monitor.) The program is given in Listing 1.1.

Listing 1.1 [Link]


class 1 public class Welcome {
main method 2 public static void main(String[] args) {
display message 3 // Display message Welcome to Java! on the console
4 [Link]("Welcome to Java!");
5 }
VideoNote
6 }
Your first Java program

Welcome to Java!

line numbers Note the line numbers are for reference purposes only; they are not part of the program. So,
don’t type line numbers in your program.
1.7 A Simple Java Program 35
Line 1 defines a class. Every Java program must have at least one class. Each class has a
name. By convention, class names start with an uppercase letter. In this example, the class class name
name is Welcome.
Line 2 defines the main method. The program is executed from the main method. A class main method
may contain several methods. The main method is the entry point where the program begins
execution.
A method is a construct that contains statements. The main method in this program contains
the [Link] statement. This statement displays the string Welcome to Java!
on the console (line 4). String is a programming term meaning a sequence of characters. A string
string must be enclosed in double quotation marks. Every statement in Java ends with a semi-
colon (;), known as the statement terminator. statement terminator
Reserved words, or keywords, have a specific meaning to the compiler and cannot be used reserved word
for other purposes in the program. For example, when the compiler sees the word class, it keyword
understands that the word after class is the name for the class. Other reserved words in this
program are public, static, and void.
Line 3 is a comment that documents what the program is and how it is constructed. Comments comment
help programmers to communicate and understand the program. They are not programming
statements, and thus are ignored by the compiler. In Java, comments are preceded by two
slashes (//) on a line, called a line comment, or enclosed between /* and */ on one or several line comment
lines, called a block comment or paragraph comment. When the compiler sees //, it ignores block comment
all text after // on the same line. When it sees /*, it scans for the next */ and ignores any text
between /* and */. Here are examples of comments:
// This application program displays Welcome to Java!
/* This application program displays Welcome to Java! */
/* 
This application program
displays Welcome to Java! */

A pair of braces in a program forms a block that groups the program’s components. In Java, block
each block begins with an opening brace ({) and ends with a closing brace (}). Every class has
a class block that groups the data and methods of the class. Similarly, every method has a
method block that groups the statements in the method. Blocks can be nested, meaning that
one block can be placed within another, as shown in the following code:

public class Welcome {


public static void main(String[] args) { Class block
[Link]("Welcome to Java!"); Method block
}
}

Tip
An opening brace must be matched by a closing brace. Whenever you type an opening match braces
brace, immediately type a closing brace to prevent the missing-brace error. Most Java
IDEs automatically insert the closing brace for each opening brace.

Caution
Java source programs are case sensitive. It would be wrong, for example, to replace main case sensitive
in the program with Main.

You have seen several special characters (e.g., { }, //, ;) in the program. They are used special characters
in almost every program. Table 1.2 summarizes their uses.
The most common errors you will make as you learn to program will be syntax errors. Like common errors
any programming language, Java has its own syntax, and you need to write code that conforms
36 Chapter 1   Introduction to Computers, Programs, and Java™
Table 1.2 Special Characters
Character Name Description
{} Opening and closing braces Denote a block to enclose statements.
() Opening and closing parentheses Used with methods.
[] Opening and closing brackets Denote an array.
// Double slashes Precede a comment line.
"" Opening and closing quotation marks Enclose a string (i.e., sequence of characters).
; Semicolon Mark the end of a statement.

syntax rules to the syntax rules. If your program violates a rule—for example, if the semicolon is missing,
a brace is missing, a quotation mark is missing, or a word is misspelled—the Java compiler
will report syntax errors. Try to compile the program with these errors and see what the com-
piler reports.

Note
You are probably wondering why the main method is defined this way and why
­[Link](...) is used to display a message on the console. For the
time being, simply accept that this is how things are done. Your questions will be fully
answered in subsequent chapters.

The program in Listing 1.1 displays one message. Once you understand the program, it
is easy to extend it to display more messages. For example, you can rewrite the program to
display three messages, as shown in Listing 1.2.

Listing 1.2 [Link]


class 1 public class WelcomeWithThreeMessages {
main method 2 public static void main(String[] args) {
display message 3 [Link]("Programming is fun!");
4 [Link]("Fundamentals First");
5 [Link]("Problem Driven");
6 }
7 }

Programming is fun!
Fundamentals First
Problem Driven

Further, you can perform mathematical computations and display the result on the console.
10.5 + 2 * 3
Listing 1.3 gives an example of evaluating .
45 - 3.5

Listing 1.3 [Link]


class 1 public class ComputeExpression {
main method 2 public static void main(String[] args) {
compute expression 3 [Link]("(10.5 + 2 * 3) / (45 – 3.5) = ");
4 [Link]((10.5 + 2 * 3) / (45 – 3.5));
5 }
6 }

(10.5 + 2 * 3) / (45 – 3.5) = 0.39759036144578314


1.8 Creating, Compiling, and Executing a Java Program 37
The print method in line 3 print vs. println
[Link]("(10.5 + 2 * 3) / (45 – 3.5) = ");

is identical to the println method except that println moves to the beginning of the next
line after displaying the string, but print does not advance to the next line when completed.
The multiplication operator in Java is *. As you can see, it is a straightforward process to
translate an arithmetic expression to a Java expression. We will discuss Java expressions fur­
ther in Chapter 2.

1.7.1 What is a keyword? List some Java keywords. Check


1.7.2 Is Java case sensitive? What is the case for Java keywords? Point
1.7.3 What is a comment? Is the comment ignored by the compiler? How do you denote a
comment line and a comment paragraph?
1.7.4 What is the statement to display a string on the console?
1.7.5 Show the output of the following code:
public class Test {
public static void main(String[] args) {
[Link]("3.5 * 4 / 2 – 2.5 is ");
[Link](3.5 * 4 / 2 – 2.5);
}
}

1.8 Creating, Compiling, and Executing a Java Program


You save a Java program in a .java file and compile it into a .class file. The .class file
is executed by the Java Virtual Machine (JVM).
Key
You have to create your program and compile it before it can be executed. This process is Point
repetitive, as shown in Figure 1.6. If your program has compile errors, you have to modify the
program to fix them, then recompile it. If your program has runtime errors or does not produce
the correct result, you have to modify the program, recompile it, and execute it again.
You can use any text editor or IDE to create and edit a Java source-code file. This section
demonstrates how to create, compile, and run Java programs from a command window. Sec- command window
tions 1.11 and 1.12 will introduce developing Java programs using NetBeans and Eclipse. From
the command window, you can use a text editor such as Notepad to create the Java source-code
file, as shown in Figure 1.7.

Note
The source file must end with the extension .java and must have the same exact name
as the public class name. For example, the file for the source code in Listing 1.1 should
be named [Link], since the public class name is Welcome. file name [Link],

A Java compiler translates a Java source file into a Java bytecode file. The following com- compile
mand compiles [Link]:
javac [Link]

Note
You must first install and configure the JDK before you can compile and run programs.
See Supplement I.B, Installing and Configuring JDK 8, for how to install the JDK and set Supplement I.B
up the environment to compile and run Java programs. If you have trouble compiling and
running programs, see Supplement I.C, Compiling and Running Java from the Command Supplement I.C
Window. This supplement also explains how to use basic DOS commands and how to
use Windows Notepad to create and edit files. All the supplements are accessible from
the Companion Website.
38 Chapter 1   Introduction to Computers, Programs, and Java™

Create/Modify Source Code

Source code (developed by the programmer)


public class Welcome { Saved on the disk
public static void main(String[] args) {
[Link]("Welcome to Java!"); Source Code
}
}

Bytecode (generated by the compiler for JVM Compile Source Code


to read and interpret) e.g., javac [Link]

Method Welcome() If compile errors occur
0 aload_0 Stored on the disk

Method void main([Link][]) Bytecode


0 getstatic #2 …
3 ldc #3 <String "Welcome to Java!">
5 invokevirtual #4 …
8 return
Run Bytecode
e.g., java Welcome

“Welcome to Java” is displayed on the console


Welcome to Java! Result

If runtime errors or incorrect result

Figure 1.6 The Java program-development process consists of repeatedly creating/modifying source code, compiling,
and executing programs.

Figure 1.7 You can create a Java source file using Windows Notepad.

.class bytecode file If there aren’t any syntax errors, the compiler generates a bytecode file with a .class
extension. Thus, the preceding command generates a file named [Link], as shown in
Figure 1.8a. The Java language is a high-level language, but Java bytecode is a low-level
bytecode language. The bytecode is similar to machine instructions but is architecture neutral and can
Java Virtual Machine (JVM) run on any platform that has a Java Virtual Machine (JVM), as shown in Figure 1.8b. Rather
than a physical machine, the virtual machine is a program that interprets Java bytecode. This
is one of Java’s primary advantages: Java bytecode can run on a variety of hardware platforms
and operating systems. Java source code is compiled into Java bytecode, and Java bytecode is
interpreted by the JVM. Your Java code may use the code in the Java library. The JVM exe-
cutes your code along with the code in the library.
interpret bytecode To execute a Java program is to run the program’s bytecode. You can execute the bytecode
on any platform with a JVM, which is an interpreter. It translates the individual instructions in
the bytecode into the target machine language code one at a time, rather than the whole pro-
gram as a single unit. Each step is executed immediately after it is translated.
1.8 Creating, Compiling, and Executing a Java Program 39

Java Bytecode

tual Mac
compiled executed Vir h
va
by generates by

in
[Link] [Link]

Ja

e
(Java source- Java (Java bytecode Any
JVM
code file) Compiler executable file) Computer

Library Code

(a) (b)

Figure 1.8 (a) Java source code is translated into bytecode. (b) Java bytecode can be executed on any computer with
a Java Virtual Machine.

The following command runs the bytecode for Listing 1.1: run

java Welcome

Figure 1.9 shows the javac command for compiling [Link]. The compiler generates javac command
the [Link] file, and this file is executed using the java command. java command

Note
For simplicity and consistency, all source-code and class files used in this book are placed
under c:\book unless specified otherwise. c:\book

Compile
Show files
VideoNote
Compile and run a Java
program

Run

Figure 1.9 The output of Listing 1.1 displays the message “Welcome to Java!”

Caution
Do not use the extension .class in the command line when executing the program.
Use java ClassName to run the program. If you use java [Link] in
the command line, the system will attempt to fetch [Link].
java ClassName

Tip
If you execute a class file that does not exist, a NoClassDefFoundError will NoClassDefFoundError
occur. If you execute a class file that does not have a main method or you mistype
the main method (e.g., by typing Main instead of main), a NoSuchMethodError NoSuchMethodError
will occur.
40 Chapter 1   Introduction to Computers, Programs, and Java™
Note
When executing a Java program, the JVM first loads the bytecode of the class to memory
class loader using a program called the class loader. If your program uses other classes, the class loader
dynamically loads them just before they are needed. After a class is loaded, the JVM uses a
bytecode verifier program called the bytecode verifier to check the validity of the bytecode and to ensure that
the bytecode does not violate Java’s security restrictions. Java enforces strict security to make
sure Java class files are not tampered with and do not harm your computer.

Pedagogical Note
Your instructor may require you to use packages for organizing programs. For example,
use package you may place all programs in this chapter in a package named chapter1. For instructions
on how to use packages, see Supplement I.F, Using Packages to Organize the Classes in
the Text.

Check 1.8.1 What is the Java source filename extension, and what is the Java bytecode filename
Point extension?
1.8.2 What are the input and output of a Java compiler?
1.8.3 What is the command to compile a Java program?
1.8.4 What is the command to run a Java program?
1.8.5 What is the JVM?
1.8.6 Can Java run on any machine? What is needed to run Java on a computer?
1.8.7 If a NoClassDefFoundError occurs when you run a program, what is the cause
of the error?
1.8.8 If a NoSuchMethodError occurs when you run a program, what is the cause of the
error?

1.9 Programming Style and Documentation


Good programming style and proper documentation make a program easy to read and
help programmers prevent errors.
Key
Point Programming style deals with what programs look like. A program can compile and run
properly even if written on only one line, but writing it all on one line would be bad pro-
programming style gramming style because it would be hard to read. Documentation is the body of explanatory
documentation remarks and comments pertaining to a program. Programming style and documentation are
as important as coding. Good programming style and appropriate documentation reduce the
chance of errors and make programs easy to read. This section gives several guidelines. For
more detailed guidelines, see Supplement I.D, Java Coding Style Guidelines, on the Com-
panion Website.

1.9.1 Appropriate Comments and Comment Styles


Include a summary at the beginning of the program that explains what the program does, its key
features, and any unique techniques it uses. In a long program, you should also include comments
that introduce each major step and explain anything that is difficult to read. It is important to make
comments concise so that they do not crowd the program or make it difficult to read.
In addition to line comments (beginning with //) and block comments (beginning with /*),
javadoc comment Java supports comments of a special type, referred to as javadoc comments. javadoc comments
begin with /** and end with */. They can be extracted into an HTML file using the JDK’s
javadoc command. For more information, see Supplement III.Y, javadoc Comments, on the
Companion Website.
1.9 Programming Style and Documentation 41
Use javadoc comments (/** . . . */) for commenting on an entire class or an entire
method. These comments must precede the class or the method header in order to be extracted
into a javadoc HTML file. For commenting on steps inside a method, use line comments (//).
To see an example of a javadoc HTML file, check out [Link]/javadoc/
[Link]. Its corresponding Java code is shown in [Link]/java-
doc/[Link].

1.9.2 Proper Indentation and Spacing


A consistent indentation style makes programs clear and easy to read, debug, and maintain.
Indentation is used to illustrate the structural relationships between a program’s compo- indent code
nents or statements. Java can read the program even if all of the statements are on the same
long line, but humans find it easier to read and maintain code that is aligned properly. Indent
each subcomponent or statement at least two spaces more than the construct within which
it is nested.
A single space should be added on both sides of a binary operator, as shown in (a), rather
in (b).

[Link](3 + 4 * 4); [Link](3+4*4);

(a) Good style (b) Bad style

1.9.3 Block Styles


A block is a group of statements surrounded by braces. There are two popular styles, next-line
style and end-of-line style, as shown below.

public class Test public class Test {


{ public static void main(String[] args) {
public static void main(String[] args) [Link]("Block Styles");
{ }
[Link]("Block Styles"); }
}
}

Next-line style End-of-line style

The next-line style aligns braces vertically and makes programs easy to read, whereas the
end-of-line style saves space and may help avoid some subtle programming errors. Both are
acceptable block styles. The choice depends on personal or organizational preference. You
should use a block style consistently—mixing styles is not recommended. This book uses the
end-of-line style to be consistent with the Java API source code.

1.9.1 Reformat the following program according to the programming style and documen-
Check
tation guidelines. Use the end-of-line brace style. Point
public class Test
{
// Main method
public static void main(String[] args) {
/** Display output */
[Link]("Welcome to Java");
}
}
42 Chapter 1   Introduction to Computers, Programs, and Java™

1.10 Programming Errors


Key Programming errors can be categorized into three types: syntax errors, runtime
Point errors, and logic errors.

1.10.1 Syntax Errors


syntax errors Errors that are detected by the compiler are called syntax errors or compile errors. Syntax
compile errors errors result from errors in code construction, such as mistyping a keyword, omitting some
necessary punctuation, or using an opening brace without a corresponding closing brace.
These errors are usually easy to detect because the compiler tells you where they are and
what caused them. For example, the program in Listing 1.4 has a syntax error, as shown in
Figure 1.10.

Listing 1.4 [Link]


1 public class ShowSyntaxErrors {
2 public static main(String[] args) {
3 [Link]("Welcome to Java);
4 }
5 }

Four errors are reported, but the program actually has two errors:
■■ The keyword void is missing before main in line 2.
■■ The string Welcome to Java should be closed with a closing quotation mark in line 3.
Since a single error will often display many lines of compile errors, it is a good practice to
fix errors from the top line and work downward. Fixing errors that occur earlier in the program
may also fix additional errors that occur later.

Compile

Figure 1.10 The compiler reports syntax errors.

Tip
If you don’t know how to correct an error, compare your program closely, character by
character, with similar examples in the text. In the first few weeks of this course, you will
fix syntax errors probably spend a lot of time fixing syntax errors. Soon you will be familiar with Java
syntax, and can quickly fix syntax errors.
1.10 Programming Errors 43

1.10.2 Runtime Errors


Runtime errors are errors that cause a program to terminate abnormally. They occur while a runtime errors
program is running if the environment detects an operation that is impossible to carry out. Input
mistakes typically cause runtime errors. An input error occurs when the program is waiting
for the user to enter a value, but the user enters a value that the program cannot handle. For
instance, if the program expects to read in a number, but instead the user enters a string, this
causes data-type errors to occur in the program.
Another example of runtime errors is division by zero. This happens when the divisor is
zero for integer divisions. For instance, the program in Listing 1.5 would cause a runtime error,
as shown in Figure 1.11.

Listing 1.5 [Link]


1 public class ShowRuntimeErrors {
2 public static void main(String[] args) {
3 [Link](1 / 0); runtime error
4 }
5 }

Run

Figure 1.11 The runtime error causes the program to terminate abnormally.

1.10.3 Logic Errors


Logic errors occur when a program does not perform the way it was intended to. Errors of this logic errors
kind occur for many different reasons. For example, suppose you wrote the program in
­Listing 1.6 to convert Celsius 35 degrees to a Fahrenheit degree:

Listing 1.6 [Link]


1 public class ShowLogicErrors {
2 public static void main(String[] args) {
3 [Link]("Celsius 35 is Fahrenheit degree ");
4 [Link]((9 / 5) * 35 + 32);
5 }
6 }

Celsius 35 is Fahrenheit degree 67

You will get Fahrenheit 67 degrees, which is wrong. It should be 95.0. In Java, the division
for integers is the quotient—the fractional part is truncated—so in Java 9 / 5 is 1. To get the
correct result, you need to use 9.0 / 5, which results in 1.8.
In general, syntax errors are easy to find and easy to correct because the compiler gives indications
as to where the errors came from and why they are wrong. Runtime errors are not difficult to find,
either, since the reasons and locations for the errors are displayed on the console when the program
aborts. Finding logic errors, on the other hand, can be very challenging. In the upcoming chapters,
you will learn the techniques of tracing programs and finding logic errors.
44 Chapter 1   Introduction to Computers, Programs, and Java™

1.10.4 Common Errors


Missing a closing brace, missing a semicolon, missing quotation marks for strings, and mis-
spelling names are common errors for new programmers.

Common Error 1: Missing Braces


The braces are used to denote a block in the program. Each opening brace must be matched
by a closing brace. A common error is missing the closing brace. To avoid this error, type a
closing brace whenever an opening brace is typed, as shown in the following example:
public class Welcome {

} Type this closing brace right away to match the opening brace.
If you use an IDE such as NetBeans and Eclipse, the IDE automatically inserts a closing
brace for each opening brace typed.

Common Error 2: Missing Semicolons


Each statement ends with a statement terminator (;). Often, a new programmer forgets to
place a statement terminator for the last statement in a block, as shown in the following
example:
public static void main(String[] args) {
[Link]("Programming is fun!");
[Link]("Fundamentals First");
[Link]("Problem Driven")
}
Missing a semicolon

Common Error 3: Missing Quotation Marks


A string must be placed inside the quotation marks. Often, a new programmer forgets to place
a quotation mark at the end of a string, as shown in the following example:
[Link]("Problem Driven);

Missing a quotation mark


If you use an IDE such as NetBeans and Eclipse, the IDE automatically inserts a closing
quotation mark for each opening quotation mark typed.

Common Error 4: Misspelling Names


Java is case sensitive. Misspelling names is a common error for new programmers. For exam-
ple, the word main is misspelled as Main and String is misspelled as string in the follow-
ing code:
1 public class Test {
2 public static void Main(string[] args) {
3 [Link]((10.5 + 2 * 3) / (45 – 3.5));
4 }
5 }

Check 1.10.1 What are syntax errors (compile errors), runtime errors, and logic errors?
Point 1.10.2 Give examples of syntax errors, runtime errors, and logic errors.
1.10.3 If you forget to put a closing quotation mark on a string, what kind error of will be raised?
1.10.4 If your program needs to read integers, but the user entered strings, an error would
occur when running this program. What kind of error is this?
1.11 Developing Java Programs Using NetBeans 45

1.10.5 Suppose you write a program for computing the perimeter of a rectangle and you mistak-
enly write your program so it computes the area of a rectangle. What kind of error is this?
1.10.6 Identify and fix the errors in the following code:
1 public class Welcome {
2 public void Main(String[] args) {
3 [Link]('Welcome to Java!);
4 }
5 )

Note
Section 1.8 introduced developing programs from the command line. Many of our ­readers
also use an IDE. The following two sections introduce two most popular Java IDEs:
NetBeans and Eclipse. These two sections may be skipped.

1.11 Developing Java Programs Using NetBeans


You can edit, compile, run, and debug Java Programs using NetBeans.
NetBeans and Eclipse are two free popular integrated development environments for develop- Key
ing Java programs. They are easy to learn if you follow simple instructions. We recommend Point
that you use either one for developing Java programs. This section gives the essential instruc-
tions to guide new users to create a project, create a class, compile, and run a class in NetBeans.
The use of Eclipse will be introduced in the next section. For instructions on downloading and VideoNote

installing latest version of NetBeans, see Supplement II.B. NetBeans brief tutorial

1.11.1 Creating a Java Project


Before you can create Java programs, you need to first create a project. A project is like a folder
to hold Java programs and all supporting files. You need to create a project only once. Here
are the steps to create a Java project:
1. Choose File, New Project to display the New Project dialog box, as shown in Figure 1.12.
2. Select Java in the Categories section and Java Application in the Projects section, and
then click Next to display the New Java Application dialog box, as shown in Figure 1.13.
3. Type demo in the Project Name field and c:\michael in Project Location field. Uncheck
Use Dedicated Folder for Storing Libraries and uncheck Create Main Class.
4. Click Finish to create the project, as shown in Figure 1.14.

Figure 1.12 The New Project dialog is used to create a new project and specify a project type.
Source: Copyright © 1995–2016 Oracle and/or its affiliates. All rights reserved. Used with
permission.
46 Chapter 1   Introduction to Computers, Programs, and Java™

Figure 1.13 The New Java Application dialog is for specifying a project name and location.
Source: Copyright © 1995–2016 Oracle and/or its affiliates. All rights reserved. Used with
permission.

Figure 1.14 A New Java project named demo is created. Source: Copyright © 1995–2016
­Oracle and/or its affiliates. All rights reserved. Used with permission.

1.11.2 Creating a Java Class


After a project is created, you can create Java programs in the project using the following steps:
1. Right-click the demo node in the project pane to display a context menu. Choose New,
Java Class to display the New Java Class dialog box, as shown in Figure 1.15.
2. Type Welcome in the Class Name field and select the Source Packages in the Location
field. Leave the Package field blank. This will create a class in the default package.
3. Click Finish to create the Welcome class. The source-code file [Link] is placed
under the <default package> node.
4. Modify the code in the Welcome class to match Listing 1.1 in the text, as shown in
Figure 1.16.

1.11.3 Compiling and Running a Class


To run [Link], right-click [Link] to display a context menu and choose Run File,
or simply press Shift + F6. The output is displayed in the Output pane, as shown in ­Figure 1.16.
The Run File command automatically compiles the program if the program has been changed.
1.12 Developing Java Programs Using Eclipse 47

Figure 1.15 The New Java Class dialog box is used to create a new Java class. Source: Copyright © 1995–2016
Oracle and/or its affiliates. All rights reserved. Used with permission.

Edit pane

Output pane

Figure 1.16 You can edit a program and run it in NetBeans. Source: Copyright © 1995–2016 Oracle and/or its
affiliates. All rights reserved. Used with permission.

1.12 Developing Java Programs Using Eclipse


You can edit, compile, run, and debug Java Programs using Eclipse.
The preceding section introduced developing Java programs using NetBeans. You can also use Key
Eclipse to develop Java programs. This section gives the essential instructions to guide new Point
users to create a project, create a class, and compile/run a class in Eclipse. For instructions on
downloading and installing latest version of Eclipse, see Supplement II.D.

1.12.1 Creating a Java Project


Before creating Java programs in Eclipse, you need to first create a project to hold all files. VideoNote
Here are the steps to create a Java project in Eclipse:
Eclipse brief tutorial
1. Choose File, New, Java Project to display the New Project wizard, as shown in Figure 1.17.
2. Type demo in the Project name field. As you type, the Location field is automatically set
by default. You may customize the location for your project.
48 Chapter 1   Introduction to Computers, Programs, and Java™

Figure 1.17 The New Java Project dialog is for specifying a project name and the properties.
Source: Eclipse Foundation, Inc.

3. Make sure you selected the options Use project folder as root for sources and class files
so the .java and .class files are in the same folder for easy access.
4. Click Finish to create the project, as shown in Figure 1.18.

Figure 1.18 A New Java project named demo is created. Source: Eclipse Foundation, Inc.
1.12 Developing Java Programs Using Eclipse 49

1.12.2 Creating a Java Class


After a project is created, you can create Java programs in the project using the following steps:
1. Choose File, New, Class to display the New Java Class wizard.
2. Type Welcome in the Name field.
3. Check the option public static void main(String[] args).
4. Click Finish to generate the template for the source code [Link], as shown in
Figure 1.19.

1.12.3 Compiling and Running a Class


To run the program, right-click the class in the project to display a context menu. Choose Run,
Java Application in the context menu to run the class. The output is displayed in the Console
pane, as shown in Figure 1.20. The Run command automatically compiles the program if the
program has been changed.

Figure 1.19 The New Java Class dialog box is used to create a new Java class. Source: Eclipse
Foundation, Inc.
54 Chapter 1   Introduction to Computers, Programs, and Java™

*1.13 (Algebra: solve 2 * 2 linear equations) You can use Cramer’s rule to solve the
following 2 * 2 system of linear equation provided that ad – bc is not 0:
ax + by = e ed - bf af - ec
x = y =
cx + dy = f ad - bc ad - bc
Write a program that solves the following equation and displays the value for x and
y: (Hint: replace the symbols in the formula with numbers to compute x and y. This
exercise can be done in Chapter 1 without using materials in later chapters.)
3.4x + 50.2y = 44.5
2.1x + .55y = 5.9

Note
More than 200 additional programming exercises with solutions are provided to the
instructors on the Instructor Resource Website.
50 Chapter 1   Introduction to Computers, Programs, and Java™

Edit pane

Output pane

Figure 1.20 You can edit a program and run it in Eclipse. Source: Eclipse Foundation, Inc.

Key Terms
Application Program Interface (API) 33 Java Runtime Environment (JRE) 34
assembler 29 Java Virtual Machine (JVM) 38
assembly language 29 javac command 39
bit 25 keyword (or reserved word) 35
block 35 library 33
block comment 35 line comment 35
bus 24 logic error 43
byte 25 low-level language 30
bytecode 38 machine language 29
bytecode verifier 40 main method 35
cable modem 28 memory 26
central processing unit (CPU) 25 dial-up modem 28
class loader 40 motherboard 25
comment 35 network interface card (NIC) 28
compiler 30 operating system (OS) 31
console 34 pixel 28
dot pitch 28 program 24
DSL (digital subscriber line) 28 programming 24
encoding scheme 25 runtime error 43
hardware 24 screen resolution 28
high-level language 30 software 24
integrated development environment source code 30
(IDE) 34 source program 30
interpreter 30 statement 30
java command 39 statement terminator 35
Java Development Toolkit (JDK) 34 storage devices 26
Java language specification 33 syntax error 42

Note
Supplement I.A The above terms are defined in this chapter. Supplement I.A, Glossary, lists all the key
terms and descriptions in the book, organized by chapters.
Chapter Summary   51

Chapter Summary
1. A computer is an electronic device that stores and processes data.
2. A computer includes both hardware and software.
3. Hardware is the physical aspect of the computer that can be touched.
4. Computer programs, known as software, are the invisible instructions that control the
hardware and make it perform tasks.

5. Computer programming is the writing of instructions (i.e., code) for computers to


perform.

6. The central processing unit (CPU) is a computer’s brain. It retrieves instructions from
memory and executes them.

7. Computers use zeros and ones because digital devices have two stable states, referred to
by convention as zero and one.

8. A bit is a binary digit 0 or 1.


9. A byte is a sequence of 8 bits.
10. A kilobyte is about 1,000 bytes, a megabyte about 1 million bytes, a gigabyte about 1
billion bytes, and a terabyte about 1,000 gigabytes.

11. Memory stores data and program instructions for the CPU to execute.
12. A memory unit is an ordered sequence of bytes.
13. Memory is volatile, because information is lost when the power is turned off.
14. Programs and data are permanently stored on storage devices and are moved to memory
when the computer actually uses them.

15. The machine language is a set of primitive instructions built into every computer.
16. Assembly language is a low-level programming language in which a mnemonic is used
to represent each machine-language instruction.

17. High-level languages are English-like and easy to learn and program.
18. A program written in a high-level language is called a source program.
19. A compiler is a software program that translates the source program into a machine-
language program.

20. The operating system (OS) is a program that manages and controls a computer’s activities.
21. Java is platform independent, meaning you can write a program once and run it on any
computer.

22. The Java source file name must match the public class name in the program. Java source-
code files must end with the .java extension.

23. Every class is compiled into a separate bytecode file that has the same name as the class
and ends with the .class extension.

24. To compile a Java source-code file from the command line, use the javac command.
52 Chapter 1   Introduction to Computers, Programs, and Java™
25. To run a Java class from the command line, use the java command.
26. Every Java program is a set of class definitions. The keyword class introduces a class
definition. The contents of the class are included in a block.

27. A block begins with an opening brace ({) and ends with a closing brace (}).
28. Methods are contained in a class. To run a Java program, the program must have a
main method. The main method is the entry point where the program starts when it is
executed.

29. Every statement in Java ends with a semicolon (;), known as the statement terminator.
30. Reserved words, or keywords, have a specific meaning to the compiler and cannot be
used for other purposes in the program.

31. In Java, comments are preceded by two slashes (//) on a line, called a line comment, or
enclosed between /* and */ on one or several lines, called a block comment or para-
graph comment. Comments are ignored by the compiler.

32. Java source programs are case sensitive.


33. Programming errors can be categorized into three types: syntax errors, runtime errors,
and logic errors. Errors reported by a compiler are called syntax errors or compile errors.
Runtime errors are errors that cause a program to terminate abnormally. Logic errors
occur when a program does not perform the way it was intended to.

Quiz
Answer the quiz for this chapter at [Link]/Liang. Choose this book and
click Companion Website to select Quiz.

Programming Exercises

Pedagogical Note
We cannot stress enough the importance of learning programming through exercises.
For this reason, the book provides a large number of programming exercises at various
levels of difficulty. The problems cover many application areas, including math, science,
business, financial, gaming, animation, and multimedia. Solutions to most even-­
numbered programming exercises are on the Companion Website. Solutions to most
odd-numbered programming exercises are on the Instructor Resource Website. The level
level of difficulty of difficulty is rated easy (no star), moderate (*), hard (**), or challenging (***).

1.1 (Display three messages) Write a program that displays Welcome to Java,
Learning Java Now, and Programming is fun.
­
1.2 (Display five messages) Write a program that displays I love Java five times.
*1.3 (Display a pattern) Write a program that displays the following pattern:

J
J aaa v vaaa
J J aa v v a a
J aaaa v aaaa
Programming Exercises   53

1.4 (Print a table) Write a program that displays the following table:
a a^2 a^3 a^4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256

1.5 (Compute expressions) Write a program that displays the result of


7.5 * 6.5 - 4.5 * 3
.
47.5 - 5.5
1.6 (Summation of a series) Write a program that displays the result of
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10.
1.7 (Approximate p) p can be computed using the following formula:
1 1 1 1 1
p = 4 * ¢1 - + - + - + c≤
3 5 7 9 11
1 1 1 1 1
Write a program that displays the result of 4 * ¢ 1 - + - + - ≤
3 5 7 9 11
1 1 1 1 1 1
and 4 * ¢ 1 - + - + - + ≤. Use 1.0 instead of 1 in your
3 5 7 9 11 13
program.
1.8 (Area and perimeter of a circle) Write a program that displays the area and perim-
eter of a circle that has a radius of 6.5 using the following formula:
p = 3.14159
perimeter = 2 * radius * p
area = radius * radius * p
1.9 (Area and perimeter of a rectangle) Write a program that displays the area and perim-
eter of a rectangle with a width of 5.3 and height of 8.6 using the following formula:
area = width * height
perimeter = 2 * (width + height)
1.10 (Average speed in miles) Assume that a runner runs 15 kilometers in 50 minutes
and 30 seconds. Write a program that displays the average speed in miles per hour.
(Note that 1 mile is 1.6 kilometers.)
*1.11 (Population projection) The U.S. Census Bureau projects population based on the
following assumptions:
■■ One birth every 7 seconds
■■ One death every 13 seconds
■■ One new immigrant every 45 seconds
Write a program to display the population for each of the next five years. Assume that
the current population is 312,032,486, and one year has 365 days. Hint: In Java, if
two integers perform division, the result is an integer. The fractional part is truncated.
For example, 5 / 4 is 1 (not 1.25) and 10 / 4 is 2 (not 2.5). To get an accurate result
with the fractional part, one of the values involved in the division must be a number
with a decimal point. For example, 5.0 / 4 is 1.25 and 10 / 4.0 is 2.5.
1.12 (Average speed in kilometers) Assume that a runner runs 24 miles in 1 hour, 40
minutes, and 35 seconds. Write a program that displays the average speed in
kilometers per hour. (Note 1 mile is equal to 1.6 kilometers.)

You might also like