Chapter1-Introduction To Java Programming
Chapter1-Introduction To Java Programming
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?
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:
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.
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
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.
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™
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?
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™
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
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
Run
Figure 1.11 The runtime error causes the program to terminate abnormally.
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™
} 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.
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.
installing latest version of NetBeans, see Supplement II.B. NetBeans brief tutorial
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.
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.
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
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.
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.
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.
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