Chapter 2 JAVA Programming Theoretical Framework
Chapter 2 JAVA Programming Theoretical Framework
1-2
Java Program Structure
// comments about the class
public class MyProgram class header
{
1-3
Comments
• Comments in a program are called inline
documentation
• They should explain the purpose of the program
and describe unclear processing steps
• They do not affect how a program works
• Java comments can take three forms:
// this comment runs to the end of the line
1-5
Reserved Words
• The Java reserved words:
abstract else interface switch
assert enum long synchronized
boolean extends native this
break false new throw
byte final null throws
case finally package transient
catch float private true
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfp
double int super
1-6
Java Translation
Java source
code Java
bytecode
java
Java
compiler
Bytecode Bytecode
interpreter compiler
javac
Machine
code
1-7
Syntax and Semantics
1-8
Errors
1-9
Object‐Oriented Programming
1-10
Objects
• An object has:
• state ‐ descriptive characteristics
• behavior ‐ what it can do (or what can be done to it)
• The state of a bank account includes its account number and its
current balance
• The behavior associated with a bank account includes the ability to
make deposits and withdrawals
• Note that the behavior of an object might change its state
1-11
Classes
1-12
Objects and Classes
A class An object
(the concept, blueprint) (the realization, instance)
1-13
Inheritance
• One class can be used to derive another via
inheritance
• Inheritance organizes classes into hierarchies
Account
Charge Bank
Account Account
Savings Checking
Account Account
1-14
Data and Expressions
Data and Expressions
• Focuses on:
• character strings
• primitive data
• the declaration and use of variables
• expressions and operator precedence
• data conversions
• accepting input from the user
• (Java applets)
• introduction to graphics
1-16
The println Method
• We used the println method to print a character
string
• The System.out object represents a destination
(the monitor screen) to which we can send output
object method
information provided to the method
name
(parameters)
1-17
String Concatenation: +
• The function that the + operator performs depends
on the type of the information on which it operates
• If both operands are strings, or if one is a string and
one is a number, it performs string concatenation
• If both operands are numeric, it adds them
• The + operator is evaluated left to right, but
parentheses can be used to force the order
1-18
Variables
• A variable is a name for a location in memory
• Variables must be declared by specifying their name
and the type of stored information
data type variable name
int total;
int count, temp, result;
1-19
Variable Initialization
• A variable can be given an initial value in the
declaration
int sum = 0;
int base = 32, max = 149;
1-20
Assignment
• An assignment statement changes the value of a
variable
• The assignment operator is the = sign
total = 55;
1-21
Constants
• A constant is an identifier that is similar to a variable except that it holds
the same value during its entire existence
• The compiler will issue an error if you try to change the value of a
constant
• In Java, we use the static final modifier to declare a constant
static final int MIN_HEIGHT = 69;
1-22
Primitive Data
• There are eight primitive data types in Java
• Four of them represent integers:
• byte, short, int, long
• Two of them represent floating point numbers:
• float, double
• One of them represents characters:
• char
• And one of them represents boolean values:
• boolean
1-23
Numeric Primitive Data
1-24
Characters
1-25
Boolean
• The reserved words true and false are the only valid values
for a boolean type
boolean done = false;
1-26
Expressions
• An expression is a combination of one or more
operators and operands
• Arithmetic expressions compute numeric results and
make use of the arithmetic operators:
Addition +
Subtraction -
Multiplication *
Division /
Remainder %
• If either or both operands used by an arithmetic
operator are floating point, then the result is a
floating point
1-27
Division and Remainder
• If both operands to the division operator (/) are
integers, the result is an integer (the fractional part
is discarded)
14 / 3 equals 4
8 / 12 equals 0
14 % 3 equals 2
8 % 12 equals 8
1-28
Increment and Decrement
1-29
Assignment Operators
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
1-30
Data Conversion
1-31
Assignment Conversion
• Assignment conversion occurs when a value of one type is assigned to
a variable of another
• If money is a float variable and dollars is an int variable, the
following assignment converts the value in dollars to a float
money = dollars
1-32
Data Conversion
• Promotion happens automatically when operators in expressions
convert their operands
• For example, if sum is a float and count is an int, the value of
count is converted to a floating point value to perform the following
calculation:
result = sum / count;
1-33
Casting
• Casting is the most powerful, and dangerous,
technique for conversion
• Both widening and narrowing conversions can be
accomplished by explicitly casting a value
• To cast, the type is put in parentheses in front of
the value being converted
• For example, if total and count are integers, but
we want a floating point result when dividing them,
we can cast total:
result = (float) total / count;
1-34
Reading Input
• The following line creates a Scanner object that reads
from the keyboard:
Scanner scan = new Scanner (System.in);
• Once created, the Scanner object can be used to
invoke various input methods, such as:
answer = scan.nextLine();
• The Scanner class is part of the java.util class
library
• Some Scanner methods:
• next, nextLine, nextBoolean, nextByte, nextDouble,
nextFloat, nextInt, nextLong, nextShort, hasNext,
useDelimiter, findInLine
1-35
Coordinate Systems
40
(112, 40)
Y
1-36
Applications and Applets
• A Java application is a stand‐alone program with a
main method
• A Java applet is a program that is intended to be
transported over the Web and executed using a
web browser
• An applet also can be executed using the appletviewer
tool of the Java Software Development Kit
• An applet doesn't have a main method
• Instead, there are several special methods that
serve specific purposes
• paint(Graphics g) is principal one
1-37
Drawing Shapes
1-40
Creating Objects
• Usually, we use the new operator to create an object
1-41
Invoking Methods
• Once an object has been instantiated, we can use the
dot operator to invoke its methods
count = title.length()
• Instance methods require an object in order to be
invoked
• sometimes the object is implied, usually it is explicit
num1 38
1-43
Reference Assignment
• For object references, assignment copies the
address:
name1 "Steve Jobs"
Before:
name2 "Steve Wozniak"
name2 = name1;
1-44
Aliases
• Two or more references that refer to the same object are called
aliases of each other
• One object can be accessed using multiple reference variables
• Aliases can be useful, but should be managed carefully
• Changing an object through one reference changes it for all of its
aliases, because there is really only one object
1-45
The String Class
• Because strings are so common, we don't have to use the new operator to create a String
object
1-46
String Methods
• Once a String object has been created, neither its value nor its
length can be changed
• Thus we say that an object of the String class is immutable
• However, several methods of the String class return new String
objects that are modified versions of the original
• Know the list of String methods on page 119
• charAt, compareTo, concat, equals, equalsIgnoreCase, length, replace,
substring, toLowerCase, toUpperCase
1-47
Packages
• The classes of the Java standard class library are
organized into packages
• Some of the packages in the standard class library:
Package Purpose
1-48
The import Declaration
• To use a class from a package, you can use its fully qualified name
java.util.Scanner
• Or you can import the class, and then use just the class name
import java.util.Scanner;
1-49
The Random Class
• The Random class is part of the java.util package
• Provides methods that generate pseudorandom numbers
• A Random object
• Performs complicated calculations based on a seed value to produce a stream
of seemingly random values
• Useful methods:
• nextInt(), nextInt(int x), nextFloat(), nextDouble()
1-50
The Math Class
• The Math class is part of the java.lang package
• The Math class contains static methods that perform various
mathematical functions
• Invoked using the class name, no object required
• These include:
• absolute value (abs)
• square root (sqrt)
• exponentiation (pow)
• trigonometric functions (sin, cos, tan, asin, acos, atan)
• max, min, floor, ceil, round, toDegrees, toRadians
1-51
Enumerated Types
1-52
Wrapper Classes
• The java.lang package contains wrapper
classes that correspond to each primitive type:
Primitive Type Wrapper Class Methods of Integer class:
byte Byte
byteValue
short Short doubleValue
int Integer floatValue
long Long intValue
longValue
float Float
double Double parseInt
char Character
toBinaryString
boolean Boolean toHexString
void Void toOctalString
1-53
Autoboxing
1-55
GUI Containers
• A GUI container is a component that is used to hold and organize other
components
• A frame is a container that is used to display a GUI‐based Java application
• A frame is displayed as a separate window with a title bar – it can be
repositioned and resized on the screen as needed
• A panel is a container that cannot be displayed on its own but is used to
organize other components
• A panel must be added to another container to be displayed
1-56
Labels
• A label is a GUI component that displays a line of text
• Labels are usually used to display information or identify other
components in the interface
1-57
WRITING CLASSES
Writing Classes
• We've been using predefined classes. Now we will learn to write our own
classes to define objects
• Chapter 4 focuses on:
• class definitions
• instance data
• encapsulation and Java modifiers
• method declaration and parameter passing
• constructors
• graphical objects
• events and listeners
• buttons and text fields
1-59
Classes and Objects
• Recall from our overview of objects in Chapter 1 that an
object has state and behavior
• Consider a six‐sided die (singular of dice)
• It’s state can be defined as which face is showing
• It’s primary behavior is that it can be rolled
Method declarations
1-61
Classes
• The values of the instance data define the state of an object created
from the class
• The functionality of the instance methods define the behavior of the
object
• For our Die class, we might declare an integer that represents the
current value showing on the face
• One of the methods would “roll” the die by setting that value to a
random number between one and six
1-62
The toString Method
• All classes that represent objects should define a toString method
• The toString method returns a character string that represents
the object in some way
• It is called automatically when an object is concatenated to a string or
when it is passed to the println method
1-63
Constructors
• A constructor is a special method that is used to set up an object
when it is initially created
• A constructor has the same name as the class
• The Die constructor is used to set the initial face value of each new
die object to one
1-64
Data Scope
• The scope of data is the area in a program in which that data can be
referenced (used)
• Data declared at the class level can be referenced by all methods in
that class
• instance data (nonstatic)
• class data (static)
1-65
Instance Data
• Instance data is called that because each instance
(object) that is created has its own version of it
• A class declares the type of the data, but it does not
reserve any memory space for it
• The objects of a class share the method definitions,
but each object has its own data space
• That's the only way two objects can have different
states
1-66
Instance Data
• We can depict two Die objects as follows:
die1 faceValue 5
die2 faceValue 2
1-67
Encapsulation
1-68
Visibility Modifiers
• Members of a class that are declared with
• public visibility can be referenced anywhere
• private visibility can be referenced only within that class
• protected visibility can be referenced by any class which inherits from that
class and any class in the same package
1-69
Visibility Modifiers
public private
Variables
Violate Enforce
encapsulation encapsulation
Support other
Methods
Provide services
methods in the
to clients
class
1-70
Method Decomposition
1-71
Accessors and Mutators
• Because instance data is private, a class usually
provides services to access and modify data values
• An accessor method returns the current value of a
variable
• A mutator method changes the value of a variable
• The names of accessor and mutator methods take
the form getX and setX, respectively, where X is
the name of the value
• They are sometimes called “getters” and “setters”
1-72
Method Declarations
• A method declaration specifies the code that will be
executed when the method is invoked (called)
• When a method is invoked, the flow of control
jumps to the method and executes its code
• When complete, the flow returns to the place
where the method was called and continues
• The invocation may or may not return a value,
depending on how the method is defined
• Even if the method returns a value, it will only be used if
the method call is part of an expression
1-73
Method Control Flow
• If the called method is in the same class, only the
method name is needed
compute myMethod
myMethod();
1-74
Method Control Flow
• The called method is often part of another class or
object
main doIt helpMe
obj.doIt(); helpMe();
1-75
Method Header
• A method declaration begins with a method header
char calc (int num1, int num2, String message)
method
parameter list
name
1-76
Method Body
• The method header is followed by the method body
char calc (int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt (sum);
• The return type of a method indicates the type of value that the
method sends back to the calling location
• A method that does not return a value has a void return type
• A return statement specifies the value that will be returned
return expression;
1-78
Parameters
• When a method is called, the actual parameters in
the invocation are copied into the formal
parameters in the method header
ch = obj.calc (25, count, "Hello");
return result;
}
1-79
Local Data
1-80
Constructors Revisited
• A constructor has no return type specified in the method header, not even
void
• A common error is to put a return type on a constructor, which makes it a
“regular” method that happens to have the same name as the class
• The programmer does not have to define a constructor for a class
• If a class has no programmer‐defined constructor, the compiler will declare a no‐
argument constructor with a body that calls super() (default constructor)
• If the programmer defines a constructor, the compiler will not define a default
constructor
1-81
Graphical User Interfaces
• A Graphical User Interface (GUI) in Java is created
with at least three kinds of objects:
• components
• events
• listeners
• The Java standard class library contains several classes that represent
typical events
• Components, such as a graphical button, generate (or fire) an event
when it occurs
• A listener object "waits" for an event to occur and responds
accordingly
• We can design listener objects to take whatever actions are
appropriate when an event occurs
1-84
Events and Listeners
Event
Component Listener
1-85
Buttons
1-86
Text Fields
• A text field is a component that allows the user to enter one line of
input
• If the cursor is in the text field, the text field component generates an
action event when the enter key is pressed
1-87
CONDITIONALS AND LOOPS
Conditionals and Loops
• This chapter covers programming statements that allow us to:
• make decisions
• repeat processing steps in a loop
1-89
Flow of Control
• Unless specified otherwise, the order of statement
execution through a method is linear: one
statement after another in sequence
• Some programming statements allow us to:
• decide whether or not to execute a particular statement
• execute a statement over and over, repetitively
if ( condition )
statement;
1-92
Boolean Expressions
• A condition often uses one of Java's equality
operators or relational operators, which all return
boolean results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
1-93
Logical Operators
• Boolean expressions can also use the following
logical operators:
! Logical NOT
&& Logical AND
|| Logical OR
• They all take boolean operands and produce
boolean results
• Logical NOT is a unary operator (it operates on one
operand)
• Logical AND and logical OR are binary operators
(each operates on two operands)
1-94
Short‐Circuited Operators
• The processing of logical AND and logical OR is
“short‐circuited”
• If the left operand is sufficient to determine the
result, the right operand is not evaluated
if (count != 0 && total/count > MAX)
System.out.println ("Testing…");
1-95
The if‐else Statement
• An else clause can be added to an if statement to
make an if‐else statement
if ( condition )
statement1;
else
statement2;
1-96
Block Statements
1-97
The Conditional Operator
1-98
The switch Statement
• The general switch
syntax of a switch statement is:
( expression )
switch { expression must
and case value1 : be integer type
case statement-list1 or char
are case value2 :
reserved statement-list2
words case value3 :
statement-list3
case ... If expression
Optional default matches value2,
section catches default : control jumps
unmatched statement-listN to here
values }
1-99
The break Statement
• Usually a break statement is used as the last statement in each case's
statement list
• A break statement causes control to transfer to the end of the
switch statement
• If a break statement is not used, the flow of control will continue
into the next case
• Usually this is an error
• The break statement can be used to leave a switch, while, do, or for
statement
1-100
Comparing Float Values
• You should rarely use the equality operator (==) when comparing two
floating point values (float or double)
• Two floating point values are equal only if their underlying binary
representations match exactly
• Computations often result in slight differences that may be irrelevant
• called round off errors
1-102
Comparing Strings
• Remember that in Java a character string is an object
• The equals method can be called with strings to determine if two
strings contain exactly the same characters in the same order
• Using == to compare Strings is a common error
if (name1.equals(name2))
System.out.println ("Same name");
1-103
Comparing Strings
1-104
Comparing Objects
• The == operator can be applied to objects – it returns true if the two
references are aliases of each other
• The equals method is also defined for all objects, but unless we
redefine it when we write a class, it has the same semantics as the ==
operator
• It has been redefined in the String class to compare the characters in
the two strings
• When you write a class, you can redefine the equals method to return
true under whatever conditions are appropriate
• Detail: when you override equals() you must also override
hashCode() to ensure that whenever equals returns true, the two
objects have the same hashCode()
1-105
Repetition Statements
• Repetition statements allow us to execute a
statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
• the while loop
• the do loop
• the for loop
• The programmer should choose the right kind of
loop for the situation
1-106
The while Statement
• A while statement has the following syntax:
while ( condition )
statement;
1-107
Nested Loops
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
10 * 20 = 200
1-108
The do Statement
• A do statement has the following syntax:
do
statement;
while ( condition )
1-109
The do Statement
• An example of a do loop:
int count = 0;
do
{
count++;
System.out.println (count);
} while (count < 5);
1-110
The for Statement
• A for statement has the following syntax:
The initialization The statement is
is executed once executed until the
before the loop begins condition becomes false
1-111
The for Statement
• An example of a for loop:
for (int count=1; count <= 5; count++)
System.out.println (count);
1-112
The for Statement
• The increment section can perform any calculation
for (int num=100; num > 0; num -= 5)
System.out.println (num);
1-113
The for Statement
1-114
Determining Event Sources
1-115
Dialog Boxes
• A dialog box is a window that appears on top of any currently active window
• It may be used to:
• convey information
• confirm an action
• allow the user to enter data
• pick a color
• choose a file
• A dialog box usually has a specific, solitary purpose, and the user interaction with it is brief
• The JOptionPane class provides methods that simplify the creation of some types of dialog
boxes
1-116
Check Boxes
• A check box is a button that can be toggled on or off
• It is represented by the JCheckBox class
• Unlike a push button, which generates an action
event, a check box generates an item event
whenever it changes state (is checked on or off)
• The ItemListener interface is used to define
item event listeners
• The check box calls the itemStateChanged
method of the listener when it is toggled
1-117
Radio Buttons
1-118