Lecture02 Java
Lecture02 Java
Java Fundamentals
Fifth Edition
by Tony Gaddis
Chapter Topics
• Why Java?
• The Parts of a Java Program
• The print and println Methods, and the Java API
• Variables and Literals
• Primitive Data Types
• Arithmetic Operators
• Combined Assignment Operators
• Creating named constants with final
• The String class
• Scope
• Comments
• Programming style
• Using the Scanner class for input
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-2
WHY JAVA?
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Why Java?
• The answer is that Java enables users to develop and
deploy applications on the Internet for servers, desktop
computers, and small hand-held devices. The future of
computing is being profoundly influenced by the
Internet, and Java promises to remain a big part of that
future. Java is the Internet programming language.
– Java is a general purpose programming language.
– Java is the Internet programming language.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-4
Java, Web, and Beyond
• Java can be used to develop Web applications.
• Java Applets
• Java can also be used to develop applications
for hand-held devices such as Palm and cell
phones
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-5
Java’s History
• Java was developed by a team led by James Gosling at
Sun Microsystems.
• Sun Microsystems was purchased by Oracle in 2010.
• Originally called Oak, Java was designed in 1991 for
use in embedded chips in consumer electronic
appliances.
• In 1995, renamed Java, it was redesigned for
developing Web applications.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-6
THE COMPILER AND THE
JAVA VIRTUAL MACHINE
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The Compiler and the Java Virtual Machine
• A programmer writes Java statements for a
program. These statements are known as
source code.
• A text editor is used to edit and save a Java
source code file.
– Source code files have a .java file extension.
• A compiler is a program that translates
source code into an object code.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-8
The Compiler and the Java Virtual Machine
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-9
The Compiler and the Java Virtual Machine
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-10
The Compiler and the Java Virtual Machine
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-11
Program Development Process
Saves Java statements
Text editor Source code
(.java)
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-12
Portability
• Portable means that a program may be written on one
type of computer and then run on a wide variety of
computers, with little or no modification.
• Java byte code runs on the JVM and not on any
particular CPU; therefore, compiled Java programs are
highly portable.
• JVMs exist on many platforms:
•Windows •Unix
•Mac •BSD
•Linux •Etc.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-13
Portability
• With most programming languages, portability
is achieved by compiling a program for each
CPU it will run on.
• Java provides an JVM for each platform so that
programmers do not have to recompile for
different platforms.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-14
Portability
Byte code
(.class)
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-15
OBJECT-ORIENTED
PROGRAMMING
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Object-Oriented Programming
• Java is an object-oriented programming (OOP)
language.
• OOP is a method of software development that
has its own practices, concepts, and vocabulary.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-17
Object-Oriented Programming
• Object-oriented programming is centered on
creating objects.
• An object is a software entity that contains data
and procedures.
• The data contained in an object is known as the
object’s attributes.
• Procedures or behaviors, that an object
performs are known as the object’s methods.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-18
An Everyday Example of an Object
• Think of your alarm clock as an object. It has
the following attributes:
– The current second (a value in the range of 0-59)
– The current minute (a value in the range of 0-59)
– The current hour (a value in the range of 1-12)
– The time the alarm is set for (a valid hour and
minute)
– Whether the alarm is on or off (on or off)
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-19
An Everyday Example of an Object
• As you can see, the attributes are merely data values that
define the alarm clock’s state. You, the user of the alarm
clock object, cannot directly manipulate these attributes
because they are private.
• To change an attribute’s value, you must use one of the
object’s methods. Here are some of the alarm clock
object’s methods:
– Set time
– Set alarm time
– Turn alarm on
– Turn alarm off
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-20
Object-Oriented Programming
Object
Attributes (data)
Methods
(behaviors / procedures)
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-21
Object-Oriented Programming
• OOP addresses the problem of code/data separation
through encapsulation and data hiding.
• Encapsulation refers to the combining of data and code
into a single object.
• Data hiding refers to an object’s ability to hide its data
from code that is outside the object.
• Only the object’s methods may then directly access and
make changes to the object’s data.
• Other objects are allowed manipulate an object’s attributes
via the object’s methods. This indirect access is known as a
programming interface.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-22
Object-Oriented Programming
Object
Attributes (data)
Programming typically private to this object
Interface
Other
objects
Methods
(behaviors / procedures)
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-23
Objects and Classes
• Classes: Where Objects Come From
– A class is code that describes a particular type of
object. It specifies the data that an object can hold
(the object's fields), and the actions that an object
can perform (the object's methods).
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-24
Metaphor: A Blueprint and Houses Built
from the Blueprint
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-25
Objects and Classes
• When a program is running, it can use the class
to create, in memory, as many objects of a
specific type as needed.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-26
PARTS OF A JAVA PROGRAM
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Parts of a Java Program
• A Java source code file contains one or more
Java classes.
– If more than one class is in a source code file,
only one of them may be public.
– The public class and the filename of the source
code file must match.
ex: A public class named Simple must be in a file named
Simple.java
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-28
Java Program
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-29
Analyzing The Example
This is a Java comment. It is
// This is a simple Java program. ignored by the compiler.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-30
Analyzing The Example
This is the method header
// This is a simple Java program. for the main method. The
main method is where a Java
public class Simple application begins.
{
public static void main(String[] args)
{ This area is the body of the main method.
All of the actions to be completed during
the main method will be between these curly braces.
}
}
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-31
Analyzing The Example
// This is a simple Java program.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-32
Parts of a Java Program
• Comments
– The line is ignored by the compiler.
– The comment in the example is a single-line comment.
• Class Header
– The class header tells the compiler things about the class
such as what other classes can use it (public) and that it is a
Java class (class), and the name of that class (Simple).
• Curly Braces
– When associated with the class header, they define the scope
of the class.
– When associated with a method, they define the scope of the
method.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-33
Parts of a Java Program
• The main Method
– This line must be exactly as shown in the example (except
the args variable name can be programmer defined).
– This is the line of code that the java command will run first.
– This method starts the Java program.
– Every Java application must have a main method.
• Java Statements
– When the program runs, the statements within the main
method will be executed.
– Can you see what the line in the example will do?
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-34
Java Statements
• If we look back at the previous example, we
can see that there is only one line that ends
with a semi-colon.
System.out.println("Programming is great fun!");
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-35
Java Statements
• Comments are ignored by the Java compiler so they
need no semi-colons.
• Other Java code elements that do not need semi colons
include:
– class headers
– method headers
– curly braces
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-36
Short Review
• Java is a case-sensitive language.
• All Java programs must be stored in a file with
a .java file extension.
• Comments are ignored by the compiler.
• A .java file may contain many classes but may
only have one public class.
• If a .java file has a public class, the class must
have the same name as the file.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-37
Short Review
• Java applications must have a main method.
• For every left brace, or opening brace, there
must be a corresponding right brace, or closing
brace.
• Statements are terminated with semicolons.
– Comments, class headers, method headers, and
braces are not considered Java statements.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-38
Special Characters
Marks the beginning of a single line
// double slash
comment.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-39
Console Output
• The console window that starts a Java application is
known as the standard output device.
• The standard input device is the keyboard.
• Java sends information to the standard output device
by using a Java class stored in the standard Java
library.
– The standard Java library is commonly referred to as the
Java Applications Programming Interface (Java API).
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-40
Console Output
• The previous example uses the line:
System.out.println("Programming is great fun!");
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-42
Console Output
• The print and println methods actually
perform the task of sending characters to the
output device.
• The line:
System.out.println("Programming is great fun!");
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-43
Console Output
• The println method places a newline
character at the end of whatever is being
printed out.
• The following lines:
System.out.println("This is being printed out");
System.out.println("on two separate lines.");
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-44
Console Output
• The print statement works very similarly to the
println statement.
• However, the print statement does not put a
newline character at the end of the output.
• The lines:
System.out.print("These lines will be");
System.out.print("printed on");
System.out.println("the same line.");
Will output:
These lines will beprinted onthe same line.
Notice the odd spacing? Why are some words run together?
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-45
Console Output
• For all of the previous examples, we have been printing
out strings of characters. Later, we will see that much
more can be printed.
• There are some special characters that can be put into
the output.
System.out.print("This line will have a newline at the end.\n");
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-46
Java Escape Sequences
\n newline Advances the cursor to the next line for subsequent printing
\t tab Causes the cursor to skip over to the next tab stop
\b backspace Causes the cursor to back up, or move left, one position
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-47
Java Escape Sequences
• Even though the escape sequences are comprised of
two characters, they are treated by the compiler as a
single character.
System.out.print("These are our top sellers:\n");
System.out.print("\tComputer games\n\tCoffee\n ");
System.out.println("\tAspirin");
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-48
VARIABLES AND LITERALS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Variables and Literals
• A variable is a named storage location in the
computer’s memory.
• A literal is a value of certain type.
• Programmers determine the number and type of
variables a program will need.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-50
Variables and Literals
See example:Variable.java
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-51
Variables and Literals
This line is called The following line is known
a variable declaration. as an assignment statement.
int value; value = 5;
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-52
The + Operator
• The + operator can be used in two ways.
– as a concatenation operator
– as an addition operator
• If either side of the + operator is a string,
the result will be a string.
System.out.println("Hello " + "World");
System.out.println("The value is: " + 5);
System.out.println("The value is: " + value);
System.out.println("The value is: " + ‘\n’ + 5);
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-53
String Concatenation
• A string literal value cannot span lines in a Java
source code file.
System.out.println("This line is too long and now it
has spanned more than one line, which will cause a
syntax error to be generated by the compiler. ");
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-54
String Concatenation
• The String concatenation operator can be used
to fix this problem.
System.out.println("These lines are " +
"now ok and will not " +
"cause the error as before.");
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-55
String Concatenation
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-56
Identifiers
• Identifiers are programmer-defined names for:
– classes
– variables
– methods
• Identifiers may not be any of the Java reserved
keywords.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-57
Identifiers
• Identifiers must follow certain rules:
– An identifier may only contain:
• letters a–z or A–Z,
• the digits 0–9,
• underscores (_), or
• the dollar sign ($)
– The first character may not be a digit.
– Identifiers are case sensitive.
• itemsOrdered is not the same as itemsordered.
– Identifiers cannot include spaces.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-58
Java Reserved Keywords
abstract double instanceof static
assert else int strictfp
boolean enum interface super
break extends long switch
byte false native synchronized
case for new this
catch final null throw
char finally package throws
class float private transient
const goto protected true
continue if public try
default implements return void
do import short volatile
while
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-59
Variable Names
• Variable names should be descriptive.
• Descriptive names allow the code to be more
readable; therefore, the code is more
maintainable.
• Which of the following is more descriptive?
double tr = 0.0725;
double salesTaxRate = 0.0725;
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-60
Java Naming Conventions
• Variable names should begin with a lower case letter
and then switch to title case thereafter:
Ex: int caTaxRate
• Class names should be all title case.
Ex: public class BigLittle
• More Java naming conventions can be found at:
http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html
• A general rule of thumb about naming variables and
classes are that, with some exceptions, their names
tend to be nouns or noun phrases.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-61
PRIMITIVE DATA TYPES
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Primitive Data Types
• Primitive data types are built into the Java language
and are not derived from classes.
• There are 8 Java primitive data types.
– byte – float
– short – double
– int – boolean
– long – char
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-63
Numeric Data Types
byte 1 byte Integers in the range
-128 to +127
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-64
Variable Declarations
• Variable Declarations take the following form:
– DataType VariableName;
• byte inches;
• short month;
• int speed;
• long timeStamp;
• float salesCommission;
• double distance;
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-65
Integer Data Types
• byte, short, int, and long are all integer
data types.
• They can hold whole numbers such as 5, 10, 23,
89, etc.
• Integer data types cannot hold numbers that
have a decimal point in them.
• Integers embedded into Java source code are
called integer literals.
• See Example: IntegerVariables.java
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-66
Integer Data Types
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-67
Floating Point Data Types
• Data types that allow fractional values are
called floating-point numbers.
– 1.7 and -45.316 are floating-point numbers.
• In Java there are two data types that can
represent floating-point numbers.
– float - also called single precision (7 decimal
points).
– double - also called double precision (15 decimal
points).
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-68
Floating Point Literals
• When floating point numbers are embedded
into Java source code they are called floating
point literals.
• The default type for floating point literals is
double.
– 29.75, 1.76, and 31.51 are double data types.
• Java is a strongly-typed language.
• See example: Sale.java
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-69
Floating Point Literals
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-70
Floating Point Literals
• A double value is not compatible with a
float variable because of its size and
precision.
– float number;
– number = 23.5; // Error!
• A double can be forced into a float by
appending the letter F or f to the literal.
– float number;
– number = 23.5F; // This will work.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-71
Floating Point Literals
• Literals cannot contain embedded currency symbols or
commas.
– grossPay = $1,257.00; // ERROR!
– grossPay = 1257.00; // Correct.
• Floating-point literals can be represented in scientific
notation.
– 47,281.97 == 4.728197 x 104.
• Java uses E notation to represent values in scientific
notation.
– 4.728197X104 == 4.728197E4.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-72
Scientific and E Notation
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-73
Scientific and E Notation
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-74
The boolean Data Type
• The Java boolean data type can have two
possible values.
– true
– false
• The value of a boolean variable may only be
copied into a boolean variable.
See example: TrueFalse.java
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-75
The boolean Data Type
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-76
The char Data Type
• The Java char data type provides access to single
characters.
• char literals are enclosed in single quote marks.
– ‘a’, ‘Z’, ‘\n’, ‘1’
• Don’t confuse char literals with string literals.
– char literals are enclosed in single quotes.
– String literals are enclosed in double quotes.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-77
The char Data Type
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-78
Variable Assignment and Initialization
• In order to store a value in a variable, an
assignment statement must be used.
• The assignment operator is the equal (=) sign.
• The operand on the left side of the assignment
operator must be a variable name.
• The operand on the right side must be either a
literal or expression that evaluates to a type that
is compatible with the type of the variable.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-79
Variable Assignment and Initialization
// This program shows variable assignment.
public class Initialize
{
public static void main(String[] args)
{
int month, days;
month = 2;
days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-80
Variable Assignment and Initialization
// This program shows variable assignment.
public class Initialize
{
public static void main(String[] args)
{
int month, days;
month = 2;
days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}
Once declared, they can then receive a value (initialization);
however the value must be compatible with the variable’s
declared type.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-81
Variable Assignment and Initialization
// This program shows variable assignment.
public class Initialize
{
public static void main(String[] args)
{
int month, days;
month = 2;
days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-82
Variable Assignment and Initialization
// This program shows variable initialization.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-83
Variable Assignment and Initialization
• Variables can only hold one value at a time.
• Local variables do not receive a default value.
• Local variables must have a valid type in order to be
used.
public static void main(String [] args)
{
int month, days; //No value given…
System.out.println("Month " + month + " has " +
days + " Days.");
}
Trying to use uninitialized variables will generate a Syntax
Error when the code is compiled.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-84
Exercise
• Suppose you earn $6000 per month and you are
allowed to contribute a portion of your gross monthly
pay to a retirement plan. You want to determine the
amount of your pay that will go into the plan if you
contribute 5 percent, 8 percent, or 10 percent of your
gross wages. Write a program to make this
determination.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-85
THE MATH CLASS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The Math class
• The Java API provides a class named Math, which
contains numerous methods that are useful for
performing complex mathematical operations. Now,
we will briefly look at the Math.pow and
Math.sqrt methods.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-87
The Math.pow Method
• In Java, raising a number to a power requires the
Math.pow method. Here is an example of how the
Math.pow method is used:
result = Math.pow(4.0,2.0);
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-88
The Math.sqrt Method
• The Math.sqrt method accepts a double value as its
argument and returns the square root of the value. Here
is an example of how the method is used:
result = Math.sqrt(9.0);
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-89
CREATING CONSTANTS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Creating Constants
• Many programs have data that does not need to be
changed.
• Littering programs with literal values can make the
program hard do read and maintain.
• Replacing literal values with constants remedies this
problem.
• Constants allow the programmer to use a name rather
than a value throughout the program.
• Constants also give a singular point for changing those
values when needed.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-91
Creating Constants
• Constants keep the program organized and easier to
maintain.
• Constants are identifiers that can hold only a single
value.
• Constants are declared using the keyword final.
• Constants need not be initialized when declared;
however, they must be initialized before they are used
or a compiler error will be generated.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-92
Creating Constants
• Once initialized with a value, constants cannot
be changed programmatically.
• By convention, constants are all upper case and
words are separated by the underscore
character.
final int CAL_SALES_TAX = 0.875;
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-93
The Math.PI Named Constant
• The Math class, which is part of the Java API, provides a
predefined named constant, Math.PI. This constant is
assigned the value 3.14159265358979323846, which is an
approximation of the mathematical value pi. For example,
look at the following statement:
area=Math.PI*radius*radius
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-94
Exercise
• Joe’s Pizza Palace needs a program to calculate the
number of pizzas a client needs to buy for a party if
each person attending is expected to eat an average of
four slices. The program should ask the user for the
number of people who will be at the party and for the
diameter of the pizzas to be ordered. It should then
calculate and display the number of pizzas to purchase.
• You must know that each slice of pizza should have an
area of 14.125 inches.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-95
COMBINED ASSIGNMENT
OPERATORS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Combined Assignment Operators
• Java has some combined assignment operators.
• These operators allow the programmer to
perform an arithmetic operation and assignment
with a single operator.
• Although not required, these operators are
popular since they shorten simple equations.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-97
Combined Assignment Operators
Operator Example Equivalent Value of variable after operation
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-98
CAST OPERATORS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Cast operators
• The cast operator lets you manually convert a value,
even if it means that a narrowing conversion will take
place. Cast operators are unary operators that appear as
a data type name enclosed in a set of parentheses. The
operator precedes the value being converted. Here is
an example:
x=(int)number;
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-100
Example uses of cast operators
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-101
THE STRING CLASS
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The String Class
• Java has no primitive data type that holds a series of
characters.
• The String class from the Java standard library is
used for this purpose.
• In order to be useful, the a variable must be created to
reference a String object.
String number;
• Notice the S in String is upper case.
• By convention, class names should always begin with
an upper case character.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-103
Primitive vs. Reference Variables
• Primitive variables actually contain the value
that they have been assigned.
number = 25;
• The value 25 will be stored in the memory
location associated with the variable number.
• Objects are not stored in variables, however.
Objects are referenced by variables.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-104
Primitive vs. Reference Variables
• When a variable references an object, it contains the
memory address of the object’s location.
• Then it is said that the variable references the object.
String cityName = “Los Angeles";
The object that contains the
character string “Los Angeles”
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-105
String Objects
• A variable can be assigned a String literal.
String message = "Hello";
• Strings are the only objects that can be created in
this way.
• A variable can be created using the new keyword.
String message = new String("Hello");
• This is the method that all other objects must use when
they are created.
See example: StringDemo.java
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-106
String Objects
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-107
The String Methods
• Since String is a class, objects that are
instances of it have methods.
• One of those methods is the length method.
stringSize = message.length();
• This statement runs the length method on the
object pointed to by the message variable.
See example: StringLength.java
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-108
The String Methods
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-109
String Methods
• charAt(index): returns the character at the
index position
• toLowerCase(): returns a new string that
is the lowercase equivalent of the string
• toUpperCase(): returns a new string that
is the uppercase equivalent of the string
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-110
String Methods
• The String class contains many methods that
help with the manipulation of String objects.
• String objects are immutable, meaning that
they cannot be changed.
• Many of the methods of a String object can
create new versions of the object.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-111
SCOPE
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Scope
• Scope refers to the part of a program that has
access to a variable’s contents.
• Variables declared inside a method (like the
main method) are called local variables.
• Local variables’ scope begins at the declaration
of the variable and ends at the end of the
method in which it was declared.
See example: Scope.java (This program contains
an intentional error.)
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-113
Scope
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-114
COMMENTING CODE
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Commenting Code
• Java provides three methods for commenting
code.
Comment
Style Description
Single line comment. Anything after the // on the line will be
//
ignored by the compiler.
Block comment. Everything beginning with /* and ending with
/* … */ the first */ will be ignored by the compiler. This comment type
cannot be nested.
Javadoc comment. This is a special version of the previous block
comment that allows comments to be documented by the javadoc
/** … */ utility program. Everything beginning with the /** and ending
with the first */ will be ignored by the compiler. This comment
type cannot be nested.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-116
READING KEYBOARD INPUT
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The Scanner Class
• To read input from the keyboard we can use the
Scanner class.
• The Scanner class is defined in java.util, so we
will use the following statement at the top of our
programs:
import java.util.Scanner;
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-118
The Scanner Class
• Scanner objects work with System.in
• To create a Scanner object:
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-119
The parts of the statement
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-120
The Scanner Class
• The Scanner class has methods for reading strings,
bytes, integers, long integers, short integers, floats, and
doubles. For example, the following code uses an
object of the Scanner class to read an int value
from the keyboard and assign the value to the number
variable.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-121
Scanner Class Methods
• Scanner keyboard = new Scanner(System.in);
Method Example
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-122
Scanner Class Methods
nextByte byte x;
x=keyboard.nextByte();
nextFloat float num4;
num4=keyboard.nextFloat();
nextDouble double num5;
num5=keyboard.nextDouble();
nextLine String name;
name=keyboard.nextLine();
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-123
Example: Payroll.java
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-124
Example: Payroll.java
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-125
Reading a Character
• The Scanner class does not have a method for reading a
single character.
• Use nextLine method to read a string from the keyboard,
then use charAt method to extract the first character.
String input;
char answer;
System.out.print(“continue?(Y=yes,N=no) ”);
input = keyboard.nextLine();
answer = input.charAt(0);
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-126
nextLine vs other Scanner methods
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-127
DIALOG BOXES
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Dialog Boxes
• A dialog box is a small graphical window that
displays a message to the user or requests input.
• A variety of dialog boxes can be displayed
using the JOptionPane class.
• • Two of the dialog boxes are:
– Message Dialog - a dialog box that displays a
message.
– Input Dialog - a dialog box that prompts the user
for input.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-129
The JOptionPane Class
• The JOptionPane class is not automatically
available to your Java programs.
• The following statement must be before the
program’s class header:
import javax.swing.JOptionPane;
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-131
Message Dialogs
• JOptionPane.showMessageDialog method is used
to display a message dialog.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-132
Input Dialogs
• An input dialog is a quick and simple way to ask the
user to enter data.
• The dialog displays a text field, an Ok button and a
Cancel button.
• If Ok is pressed, the dialog returns the user’s input.
• If Cancel is pressed, the dialog returns null.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-133
Input Dialogs
String name;
name = JOptionPane.showInputDialog("Enter your name.");
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-134
The System.exit Method
• A program that uses JOptionPane does not
automatically stop executing when the end of the main
method is reached.
• Java generates a thread, which is a process running in
the computer, when a JOptionPane is created.
• If the System.exit method is not called, this thread
continues to execute.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-135
The System.exit Method
• The System.exit method requires an integer argument.
System.exit(0);
• This argument is an exit code that is passed back to the
operating system.
• This code is usually ignored, however, it can be used
outside the program:
– to indicate whether the program ended successfully or as the
result of a failure.
– The value 0 traditionally indicates that the program ended
successfully.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-136
Dialog boxes displayed by the NamesDialog
program
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-137
JOptionPane Message Dialog
Constants
• All message dialog types except PLAIN_MESSAGE display an
icon to the left of the message. These icons provide a visual
indication of the message’s importance to the user. A
QUESTION_MESSAGE icon is the default icon for an input
dialog box.
JOptionPane.showMessageDialog(null,"Hello World!", "Message
in the Title Bar",JOptionPane.PLAIN_MESSAGE);
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Converting a String to a Number
• The JOptionPane’s showInputDialog method
always returns the user's input as a String
• A String containing a number, such as “127.89, can
be converted to a numeric data type.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-139
The Parse Methods
• Each of the numeric wrapper classes, (covered in
Chapter 10) has a method that converts a string to a
number.
– The Integer class has a method that converts a string to
an int,
– The Double class has a method that converts a string to a
– double, and
– etc.
• These methods are known as parse methods because
their names begin with the word “parse.”
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-140
The Parse Methods
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-141
Reading an Integer with an Input
Dialog
int number;
String str;
str = JOptionPane.showInputDialog("Enter a
number.");
number = Integer.parseInt(str);
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-142
Reading a double with an Input Dialog
double price;
String str;
str = JOptionPane.showInputDialog("Enter the
retail price.");
price = Double.parseDouble(str);
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2-143
Chapter 1 y 2:
Java Fundamentals
Fifth Edition
by Tony Gaddis