CPPROG2 - Lesson 1 Creating Your First Java Classes
CPPROG2 - Lesson 1 Creating Your First Java Classes
Reference Materials:
• Introduction to Java
https://www.youtube.com/watch?v=2dZiMBwX_5Q
• Installation and Hello World
https://www.youtube.com/watch?v=Hdf5OmERt0g
• Intro to Object Oriented Programming
https://www.youtube.com/watch?v=bbnEO8V865o
• Getting Started
https://docs.oracle.com/javase/tutorial/getStarted/index.html
• A Closer Look at the “Hello World” Application
https://docs.oracle.com/javase/tutorial/getStarted/application/index.html
The logic behind a computer program determines the exact order of switches that perform the
desired tasks to produce desired output. A program written in the style that refers to switch
settings is written in machine language, which is the most basic circuitry-level language. Machine
language is a low-level programming language, or one that corresponds closely to a computer
processor’s circuitry.
A high-level programming language allows you to use a vocabulary of reasonable terms, such as
read, write, or add, instead of the sequences of on and off switches that perform these tasks.
Each high-level language has its own syntax, or rules of the language. When you are learning a
computer programming language, such as Java, C++, or Visual Basic, you really are learning the
vocabulary and syntax rules for the language.
Program statements are also known as commands because they are commands to the computer
such as “write this statement” or “add these two numbers.”
Compilers and interpreters issue one or more error messages each time they encounter an
invalid program statement – that is, a statement containing a syntax error, or misuse of the
language. Locating and repairing all syntax errors is the first part of the process of debugging a
program – freeing the program of all errors. Programmers call some logical errors semantic
errors. For example, if you misspel a programming language word, you commit a syntax error,
but if you use a correct word in the wrong context, you commit a semantic error.
Procedural Programming
Procedural programming is a style of programming in which operations are executed one after
another in sequence. It involves using your knowledge of a programming language to create
applications, which are programs that perform a task for a user. In procedural applications, you
create names for computer memory locations that can hold values—for example, numbers and
text—in electronic form. The named computer memory locations are called variables because
they hold values that might vary. For convenience, the individual operations used in a computer
program are often grouped into logical units called procedures. Procedures are also called
modules, methods, functions, and subroutines. Users of different programming languages tend
to use different terms. Java programmers most frequently use the term method.
Object-Oriented Programming
Besides defining properties, classes define methods their objects can use. A method is a self-
contained block of program code that carries out some action, similar to a procedure in a
procedural program.
In object-oriented classes, attributes and methods are encapsulated into objects that are then
used much like real-world objects. Encapsulation refers to the hiding of data and methods within
an object. Encapsulation provides the security that keeps data and methods safe from
inadvertent changes.
Java can be run on a wide variety of computers because it does not execute instructions on a
computer directly. Instead, Java runs on a hypothetical computer known as the Java Virtual
Machine (JVM).
Programming statements written in a high-level programming language are called source code.
When you write a Java program, you first construct the source code using a text editor such as
Notepad. The statements are saved in a file; then, the Java compiler converts the source code
into a binary program of bytecode. A program called the Java interpreter then checks the
bytecode and communicates with the operating system, executing the bytecode instructions line
by line within the Java Virtual Machine.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
“Write once, run anywhere” (WORA) is a slogan developed by Sun Microsystems to describe the
ability of one Java program version to work correctly on multiple platforms.
You can write two kinds of programs using Java. Programs that are embedded in a Web page are
called Java applets. Stand-alone programs are called Java applications. Java applications can be
further subdivided into console applications, which support character output to a computer
screen in a DOS window, for example, and windowed applications, which create a GUI with
elements such as menus, toolbars, and dialog boxes.
The text “First Java application” is a literal string of characters; that is, it is a series of characters
that will appear in output exactly as entered. Literal string in Java must be enclosed in double
quotation marks.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
The string “First Java application” appears within parentheses because the string is an argument
to a method, and arguments to methods always appear within parentheses. Arguments are
pieces of information that are sent into, or passed to, a method, usually because the method
requires the information to perform its task or carry out its purpose. As an example, consider
placing a catalog order with a company that sells sporting goods. Processing a catalog order is a
method that consists of a set of standard procedures— recording the order, checking the
availability of the item, pulling the item from the warehouse, and so on. Each catalog order also
requires a set of data items, such as which item number you are ordering and the quantity of the
item desired; these data items can be considered the order’s arguments. If you order two of item
5432 from a catalog, you expect different results than if you order 1,000 of item 9008. Likewise,
if you pass the argument “Happy Holidays” to a Java method, you expect different results than if
you pass the argument “First Java application”.
Method names usually are referenced followed by their parentheses, as in println(), so that
you can distinguish method names from variable names
The print() method is very similar to the println() method. With println(), after the
message is displayed, the insertion point appears on the following line. With print(), the
insertion point does not advance to a new line; it remains on the same line as the output.
Java is case sensitive; the class named System is a completely different class from one named
system, SYSTEM, or even sYsTeM.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
The statement that displays the string “First Java application” cannot stand alone; it is embedded
within a class
Everything that you use within a Java program must be part of a class. When you write public
class First, you are defining a class named First. You can define a Java class using any name or
identifier you need, as long as it meets the following requirements:
• A Java identifier must begin with a letter of the English alphabet, a non-English letter (such
as α or π), an underscore, or a dollar sign. A class name cannot begin with a digit.
• A Java identifier can contain only letters, digits, underscores, or dollar signs.
• A Java identifier cannot be a reserved keyword, such as public or class. (See Table 1-1 for a
list of reserved keywords.)
• A Java identifier cannot be one of the following values: true, false, or null. These are
not keywords (they are primitive values), but they are reserved and cannot be used.
It is a Java standard, although not a requirement, to begin class identifiers with an uppercase
letter and employ other uppercase letters as needed to improve readability. Table 1-1 Java
reserved keywords lists some valid and conventional class names that you could use when writing
programs in Java. Table 1-3 provides some examples of class names that could be used in Java (if
you use these class names, the class will compile) but that are unconventional and not
recommended. Table 1-4 provides some class name examples that are illegal.
Undergradstudent New words are not indicated with initial uppercase letters,
making this identifier difficult to read
Inventory_Item Underscore is not commonly used to indicate new words
BUDGET2020 Using all uppercase letters for class identifiers is not conventional
Budget2020 Conventionally, class names do not begin with a lowercase letter
Table 1-3 Legal but unconventional and non-recommended class names in Java
In Figure 1-3 (and again in Figure 1-5), the line public class First is the class header; it
contains the keyword class, which identifies First as a class. The reserved word public is
an access specifier. An access specifier defines the circumstances under which a class can be
accessed and the other classes that have the right to use a class. Public access is the most liberal
type of access.
After the class header, you enclose the contents of a class within curly braces ( { and } ); any data
items and methods between the curly braces make up the class body. A class body can be
composed of any number of data items and methods. In Figure 1-3 (and again in Figure 1-5), the
class First contains only one method within its curly braces. The name of the method is
main(), and the main() method, like the println() method, includes its own set of
parentheses. The main() method in the First class contains only one statement—the
statement that uses the println() method.
For every opening curly brace ( { ) in a Java program, there must be a corresponding closing curly
brace ( } ). The placement of the opening and closing curly braces is not important to the
compiler. For example, the following class executes in exactly the same way as the one shown in
Figure 1-3. The only difference is the layout of the braces—the line breaks occur in different
locations.
The indent style in which curly braces are aligned and each occupies its own line is called the
Allman style, named for Eric Allman, a programmer who popularized the style. The indent style
in which opening braces are not on separate lines is known as the K & R style, named for
Kernighan and Ritchie, who wrote the first book on the C programming language.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
In the method header public static void main(String[] args), the word
public is an access specifier, just as it is when you use it to define the First class. In Java,
the reserved keyword static means that a method is accessible and usable even though no
objects of the class exist. Figure 1-6 shows the parts of the main() method.
In English, the word void means empty. When the keyword void is used in the main() method
header, it does not indicate that the main() method is empty, but rather that the main()
method does not return any value when it is called. This doesn’t mean that main() doesn’t
produce output—in fact, the method in Figure 1-3 (and in Figure 1-6) does. It only means that
the main() method does not send any value back to any other method that might use it.
Not all classes have a main() method; in fact, many do not. All Java applications, however, must
include a class containing a public method named main(), and most Java applications have
additional classes and methods. When you execute a Java application, the JVM always executes
the main() method first.
In the method header public static void main(String[] args), the contents
between the parentheses, (String[] args), represent the type of argument that can be
passed to the main() method, just as the string "First Java application" is an argument passed
to the println() method. String is a Java class that can be used to hold character strings.
The identifier args is used to hold any String objects that might be sent to the main()
method. The main() method could do something with those arguments, such as display them,
but in Figure 1-3, the main() method does not actually use the args identifier. Nevertheless,
you must place an identifier within the main() method’s parentheses. The identifier does not
need to be named args—it could be any legal Java identifier—but the name args is traditional.
The simple application shown in Figure 1-3 has many pieces to remember. However, for now you
can use the Java code shown in Figure 1-7 as a shell, in which you replace AnyClassName with a
class name you choose and the line /******/ with any statements that you want to execute.
Comments also can be useful when you are developing an application. If a program is not
performing as expected, you can “comment out” various statements and subsequently run the
program to observe the effect. When you comment out a statement, you turn it into a comment
so the compiler does not translate it, and the JVM does not execute its command. This can help
you pinpoint the location of errant statements in malfunctioning programs.
• Line comments start with two forward slashes ( // ) and continue to the end of the current
line. A line comment can appear on a line by itself or at the end (and to the right) of a line
following executable code. Line comments do not require an ending symbol.
• Block comments start with a forward slash and an asterisk ( /* ) and end with an asterisk and
a forward slash ( */ ). A block comment can appear on a line by itself, on a line before
executable code, or on a line after executable code. Block comments also can extend across
as many lines as needed.
• Javadoc comments are a special case of block comments. They begin with a forward slash
and two asterisks ( /** ) and end with an asterisk and a forward slash ( */ ). You can use
javadoc comments to generate documentation with a program named javadoc. Appendix E
teaches you how to create javadoc comments.
Figure 1-8 shows how comments are used in code. In this example, the only statement that
executes is the System.out.println("Hello"); statement; everything else (all the
shaded parts) is a comment.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
When you write a Java class, you must save it using a storage medium such as a disk, DVD, or
USB device. In Java, if a class is public (that is, if you use the public access specifier before the
class name), you must save the class in a file with exactly the same name and a .java extension.
For example, the First class must be stored in a file named First.java. The class name and
filename must match exactly, including the use of uppercase and lowercase characters. If the
extension is not .java, the Java compiler does not recognize the file as containing a Java class.
After you write and save an application, two steps must occur before you can view the
application’s output.
1. You must compile the class you wrote (called the source code) into bytecode.
2. You must use the Java interpreter to translate the bytecode into executable statements.
To compile your source code from the command line, your prompt should show the folder or
directory where your program file is stored. Then, you type javac followed by the name of the
file that contains the source code. For example, to compile a file named First.java, you type the
following and then press Enter:
javac First.java
If you receive an error message that the command is not recognized, it might mean one of the
following:
If you receive a programming language error message, there are one or more syntax errors in
the source code. Recall that a syntax error is a programming error that occurs when you
introduce typing errors into your program or use the programming language incorrectly. For
example, if your class name is first (with a lowercase f) in the source code but you saved the
file as First.java (with an uppercase F), when you compile the application you’ll receive an
error message, such as class first is public, should be declared in a
file named first.java, because first and First are not the same in a case-sensitive
language. If this error occurs, you must reopen the text file that contains the source code and
make the necessary corrections.
If you receive no error messages after compiling the code in a file named First.java, the
application compiled successfully, and a file named First.class is created and saved in the same
OBJECT-ORIENTED PROGRAMMING JAVA Programming
folder as the application text file. After a successful compile, you can run the class file on any
computer that has a Java language interpreter.
To run the First application from the command line, you type the following:
java First
Figure 1-9 shows the application’s output in the command window. In this example, you can see
that the First class is stored in a folder named Java on the C drive.
After viewing the application output, you might decide to modify the class to get a different
result. For example, you might decide to change the First application’s output from First
Java application to the following:
To produce the new output, first you must modify the text file that contains the existing class.
You need to change the existing literal string, and then add an output statement for another text
string. Figure 1-10 shows the class that changes the output.
Figure 1-10 First class containing modified output from original version
The changes to the First class include the addition of the statement
System.out.println("My new and improved"); and the removal of the word First
from the string in the other println() statement. However, if you make changes to the file
as shown in Figure 1-10, save the file, and execute the program by typing java First at the
command line, you will not see the new output—you will see the old output without the added
line. Even though you save a text file containing the modified source code for a class, it is the
compiled class in the already-compiled class file that executes. After you save the file named
First.java, the old compiled version of the class with the same name is still stored on your
computer. Before the new source code will execute, you must do the following:
OBJECT-ORIENTED PROGRAMMING JAVA Programming
1. Save the file with the changes (using the same filename).
2. Compile the class with the javac command. (Actually, you are recompiling the class.)
3. Interpret the class bytecode and execute the class using the java command.
import javax.swing.JOptionPane;
public class FirstDialog {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "First Java Dialog");
}
}
In Figure 1-12, the first shaded line is an import statement. You use an import statement when
you want to access a built-in Java class that is contained in a group of classes called a package.
To use the JOptionPane class, you must import the package named
javax.swing.JOptionPane.
The second shaded statement in theFirstDialog class in Figure 1-12 uses the
showMessageDialog() method that is part of the JOptionPane class. Like the
println() method that is used for console output, the showMessageDialog() method
is followed by a set of parentheses. However, whereas the println() method requires only
one argument between its parentheses to produce an output string, the
showMessageDialog() method requires two arguments. When the first argument to
showMessageDialog() is null, as it is in the class in Figure 1-12, it means the output
message box should be placed in the center of the screen. The second argument, after the
comma, is the string that is displayed.
When a user executes the FirstDialog class, the dialog box in Figure 1-13 is displayed. The
user must click the OK button or the Close button to dismiss the dialog box.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
This is a compile-time error, or one in which the compiler detects a violation of language syntax
rules and is unable to translate the source code to machine code.
Figure 1-14 Error message generated when program contains case error
When you compile a class, the compiler reports as many errors as it can find so that you can fix
as many errors as possible. Sometimes, one error in syntax causes multiple error messages that
normally would not be errors if the first syntax error did not exist. Consider the ErrorTest
class shown in Figure 1-15. The class contains a single error—the comment that starts in the
second line is never closed. However, when you attempt to compile this class, you receive two
error messages, as shown in Figure 1-16.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
The first error message in Figure 1-16 correctly identifies the unclosed comment. The second
error message is more confusing: “reached end of file while parsing.” Parsing is the process the
compiler uses to divide your source code into meaningful portions; the message means that the
compiler was in the process of analyzing the code when the end of the file was encountered
prematurely. If you repair the first error by closing off the comment and then save and recompile
the class, both error messages disappear. The second message is generated only as a side effect
of the unfinished comment. When you compile a class and view a list of errors, correct the errors
that make sense to you and then recompile. Sometimes, when you correct an error or two,
several others disappear. On the other hand, sometimes when you fix a compile-time error and
recompile a program, new error messages are generated. That’s because when you fix the first
error, the compiler can proceed beyond that point and possibly discover new errors. Of course,
no programmer intends to type a program containing syntax errors, but when you do, the
compiler finds them all for you.
A second kind of error occurs when the syntax of the program is correct and the program
compiles but produces incorrect results when you execute it. This type of error is a logic error,
which is usually more difficult to find and resolve. In the ErrorTest class in Figure 1-15, typing
the executable statement as System.out.println("Tst"); does not produce an error.
The compiler does not find the spelling error of Tst instead of Test; the code is compiled and the
JVM can execute the statements. Other examples of logic errors include multiplying two values
when you meant to add, printing one copy of a report when you meant to print five, or forgetting
to produce a requested count of the number of times an event has occurred. Errors of this type
must be detected by carefully examining the program output. It is the responsibility of the
program author to test programs and find any logic errors. Good programming practice
emphasizes programming structure and development that helps minimize errors.
As you write Java programs, you can frequently consult this module as well as other Java
documentation. A great wealth of helpful material exists at the Sun Microsystems Web site,
https://www.oracle.com/java/technologies. Of particular value is the Java application
programming interface, more commonly referred to as the Java API. The Java API is also called
OBJECT-ORIENTED PROGRAMMING JAVA Programming
the Java class library; it contains information about how to use every prewritten Java class,
including lists of all the methods you can use with the classes.
A downloadable Java tutorial titled “The Java” with hundreds of complete working examples is
available from https://docs.oracle.com/javase/tutorial/The tutorial is organized into trails—
groups of lessons on a particular subject. You can start the tutorial at the beginning and navigate
sequentially to the end, or you can jump from one trail to another. As you study each chapter in
this module, you are encouraged to make good use of these support materials.