0% found this document useful (0 votes)
43 views118 pages

Chapter 2 JAVA Programming Theoretical Framework

The document discusses Java programming concepts including object-oriented programming, classes, objects, inheritance, and data types. It describes key elements like main methods, variables, constants, and primitive data types in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
43 views118 pages

Chapter 2 JAVA Programming Theoretical Framework

The document discusses Java programming concepts including object-oriented programming, classes, objects, inheritance, and data types. It describes key elements like main methods, variables, constants, and primitive data types in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 118

CHAPTER 2

JAVA PROGRAMMING THEORETICAL


FRAMEWORK
Eng. glmoyo
Focus of the Course
• Object‐Oriented Software Development
• problem solving
• program design, implementation, and testing
• object‐oriented concepts
• classes
• objects
• encapsulation
• inheritance
• polymorphism

• graphical user interfaces


• the Java programming language

1-2
Java Program Structure
// comments about the class
public class MyProgram class header
{

// comments about the method


public static void main (String[] args)
class {
body
method header
method body
}

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

/* this comment runs to the terminating


symbol, even across line breaks */

/** this is a javadoc comment */


1-4
Identifiers

• Identifiers are the words a programmer uses in a program


• An identifier can be made up of letters, digits, the underscore character ( _
), and the dollar sign
• Identifiers cannot begin with a digit
• Java is case sensitive ‐ Total, total, and TOTAL are different
identifiers
• By convention, programmers use different case styles for different types of
identifiers, such as
• title case for class names ‐ Lincoln
• upper case for constants ‐ MAXIMUM

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

• Syntax rules define how we can put together symbols, reserved


words, and identifiers to make a valid program
• Semantics define what statements mean
• its purpose or role in a program

• A program that is syntactically correct is not necessarily logically


(semantically) correct

1-8
Errors

• A program can have three types of errors:


• The compiler will find syntax errors and other basic problems
(compile‐time errors)
• A problem can occur during program execution, such as trying to
divide by zero, which causes a program to terminate abnormally (run‐
time errors)
• A program may run, but produce incorrect results, perhaps using an
incorrect formula (logical errors)

1-9
Object‐Oriented Programming

• Java is an object‐oriented programming language


• An object is a fundamental entity in a Java program
• Objects can be used effectively to represent real‐world entities
• For example, an object might represent a particular employee in a
company
• Each employee object handles the processing and data management related
to that employee

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

• An object is defined by a class


• A class is the blueprint of an object
• The class uses methods to define the behaviors of the object
• The class that contains the main method of a Java program represents
the entire program
• A class represents a concept, and an object represents the
embodiment of that concept
• Multiple objects can be created from the same class

1-12
Objects and Classes
A class An object
(the concept, blueprint) (the realization, instance)

Bank John’s Bank Account


Account Balance: $5,257

Bill’s Bank Account


Balance: $1,245,069
Multiple objects
from the same class
Mary’s Bank Account
Balance: $16,833

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

System.out.println ("Whatever you are, be a good one.");

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;

Multiple variables can be created in one declaration

1-19
Variable Initialization
• A variable can be given an initial value in the
declaration
int sum = 0;
int base = 32, max = 149;

• When a variable is referenced in a program, its


current value is used
 value can be changed by assignment

1-20
Assignment
• An assignment statement changes the value of a
variable
• The assignment operator is the = sign
total = 55;

• The expression on the right is evaluated and the


result is stored in the variable on the left
• The value that was in total is overwritten
• You can only assign a value to a variable that is
consistent with the variable's declared type

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;

• final indicates the value cannot change


• static indicates all objects of the class share one copy of the constant

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

• The difference between the various numeric primitive types is their


size, and therefore the values they can store:
Type Storage Min Value Max Value

byte 8 bits -128 127


short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits < -9 x 1018 > 9 x 1018

float 32 bits +/- 3.4 x 1038 with 7 significant digits


double 64 bits +/- 1.7 x 10308 with 15 significant digits

1-24
Characters

• A char variable stores a single character


• Character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' '\n'
• Example declarations:

char topGrade = 'A';


char terminator = ';', separator = ' ';
• Note the distinction between a primitive character variable, which holds only one character, and a
String object, which can hold multiple characters

1-25
Boolean

• A boolean value represents a true or false condition

• The reserved words true and false are the only valid values
for a boolean type
boolean done = false;

• A boolean variable can also be used to represent any two states,


such as a light bulb being on or off

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

• The remainder operator (%) returns the remainder


after dividing the second operand into the first

14 % 3 equals 2

8 % 12 equals 8

1-28
Increment and Decrement

• The increment and decrement operators can be applied in postfix form:


count++
• or prefix form:
++count
• When used as part of a larger expression, the two forms can have different
effects
• Because of their subtleties, the increment and decrement operators should
be used with care

1-29
Assignment Operators

• There are many assignment operators in Java, including the following:

Operator Example Equivalent To

+= 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

• Conversions must be handled carefully to avoid losing information


• Widening conversions are safest because they tend to go from a small
data type to a larger one (such as a short to an int)
• Narrowing conversions can lose information because they tend to go
from a large data type to a smaller one (such as an int to a short)
• In Java, data conversions can occur in three ways:
• assignment conversion
• promotion
• casting

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

• Only widening conversions can happen via assignment


• Note that the value or type of dollars did not change

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

• Each pixel can be identified using a two‐dimensional coordinate


system
• When referring to a pixel in a Java program, we use a coordinate
system with the origin in the top‐left corner
(0, 0) 112 X

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

• The Graphics class has methods to draw shapes


• drawLine, drawRect, drawOval, drawString, drawArc, fillRect, fillOval, fillArc,
getColor, setColor
• A shape can be filled or unfilled, depending on which method is
invoked
• The method parameters specify coordinates and sizes
• Shapes with curves, like an oval, are usually drawn by specifying the
shape’s bounding rectangle
• An arc can be thought of as a section of an oval
1-38
USING CLASSES AND OBJECTS
Using Classes and Objects
• focuses on:
• object creation and object references
• the String class and its methods
• the Java standard class library
• the Random and Math classes
• (formatting output)
• (enumerated types)
• wrapper classes
• graphical components and containers
• labels and images

1-40
Creating Objects
• Usually, we use the new operator to create an object

title = new String ("Java Software Solutions");

This calls the String constructor, which is


a special method that sets up the object

• Creating an object is called instantiation

• An object is an instance of a particular class

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

• A method may return a value, which can be used in an


assignment or expression
• A method invocation can be thought of as asking an
object to perform a service
1-42
References
• Note:
• primitive variables contain the value itself
• object variables contain the address of the object

• Object references can be thought of as pointers to the location of the


object
• Rather than dealing with arbitrary addresses, we often depict a
reference graphically

num1 38

name1 "Steve Jobs"

1-43
Reference Assignment
• For object references, assignment copies the
address:
name1 "Steve Jobs"
Before:
name2 "Steve Wozniak"

name2 = name1;

name1 "Steve Jobs"


After:
name2

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

title = "Java Software Solutions";

• This is special syntax that works only for strings

• Each string literal (enclosed in double quotes) represents a String object

• It is possible for different String objects to have the same characters

• Characters og a string referenced by their index (charAt(i))


• index starts at 0

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

java.lang General support


java.applet Creating applets for the web
java.awt Graphics and graphical user interfaces
javax.swing Additional graphics capabilities
java.net Network communication
java.util Utilities
javax.xml.parsers XML document processing

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;

• To import all classes in a particular package, you can use the *


wildcard character
import java.util.*;

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

• Java allows you to define an enumerated type, which can then be


used to declare variables
• An enumerated type lists all possible values for a variable of that type
• The values are identifiers of your own choosing
• The following declaration creates an enumerated type called Season
enum Season {winter, spring, summer, fall};

• Any number of values can be listed

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

• Autoboxing is the automatic conversion of a primitive value to a


corresponding wrapper object:
Integer obj;
int num = 42;
obj = num;
• The assignment creates the appropriate Integer object
• The reverse conversion (called unboxing) also occurs automatically as
needed
1-54
GUI Components
• A GUI component is an object that represents a screen element such as a
button or a text field
• GUI‐related classes are defined primarily in the java.awt and the
javax.swing packages
• The Abstract Windowing Toolkit (AWT) was the original Java GUI package
• The Swing package provides additional and more versatile components
• Both packages are needed to create a Java GUI‐based program

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

• We can represent a die in software by designing a class


called Die that models this state and behavior
• The class serves as the blueprint for a die object

• We can then instantiate as many die objects as we need


for any particular program
1-60
Classes

• A class can contain data declarations and method declarations


int size, weight;
Data declarations
char category;

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)

• Data declared within a method can be used only in that method


• local data

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

Each object maintains its own faceValue


variable, and thus its own state

1-67
Encapsulation

• We can take one of two views of an object:


• internal ‐ the details of the variables and methods of the class that defines it
• external ‐ the services that an object provides and how the object interacts
with the rest of the system

• From the external view, an object is an encapsulated entity, providing


a set of specific services
• These services define the interface to the object

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

• Members declared without a visibility modifier have default visibility


and can be referenced by 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

• A method should be relatively small, so that it can be understood as a


single entity
• A potentially large method should be decomposed into several
smaller methods as needed for clarity
• A public service method of an object may call one or more private
support methods to help it accomplish its goal
• Support methods might call other support methods if appropriate

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

return The parameter list specifies the type


type and name of each parameter

The name of a parameter in the method


declaration is called a formal parameter

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);

return result; sum and result


} are local data

They are created


The return expression each time the
must be consistent with method is called, and
the return type are destroyed when
it finishes executing
1-77
The return Statement

• 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;

• Its expression must conform to the return type

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");

char calc (int num1, int num2, String message)


{
int sum = num1 + num2;
char result = message.charAt (sum);

return result;
}
1-79
Local Data

• Local variables can be declared inside a method


• The formal parameters of a method create automatic local variables
when the method is invoked
• When the method finishes, all local variables are destroyed (including
the formal parameters)
• instance variables, declared at the class level, exists as long as the
object exists
• static variables exist as long as the class exists

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

• Components are objects that represent screen


elements
• labels, buttons, text fields, menus, etc.

• Some components are containers that hold and


organize other components
• frames, panels, applets, dialog boxes
1-82
Events
• An event is an object that represents some activity to
which we may want to respond
• For example, we may want our program to perform
some action when the following occurs:
• the mouse is moved
• the mouse is dragged
• a mouse button is clicked
• a graphical button is clicked
• a keyboard key is pressed
• a timer expires

• Events often correspond to user actions, but not always


1-83
Events and 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

A component object A corresponding listener


may generate an event object is designed to
respond to the event

When the event occurs, the component calls


the appropriate method of the listener,
passing an object that describes the event

1-85
Buttons

• A push button is a component that allows the user to initiate an


action by pressing a graphical button using the mouse
• A push button is defined by the JButton class
• It generates an action event

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

• Chapter 5 focuses on:


• boolean expressions
• conditional statements
• comparing data
• repetition statements
• iterators
• more drawing techniques
• more GUI components

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

• These decisions are based on boolean expressions


(or conditions) that evaluate to true or false
• The order of statement execution is called the flow
of control
1-90
Conditional Statements
• A conditional statement lets us choose which
statement will be executed next
• They are sometimes called selection statements
• Conditional statements give us the power to make
basic decisions
• The Java conditional statements are the:
• if statement
• if‐else statement
• switch statement
1-91
The if Statement
• The if statement has the following syntax:
The condition must be a
boolean expression. It must
if is a Java evaluate to either true or false.
reserved word

if ( condition )
statement;

If the condition is true, the statement is executed.


If it is false, the statement is skipped.

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

• Note the difference between the equality operator


(==) and the assignment operator (=)

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…");

• This type of processing must be used carefully

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;

• If the condition is true, statement1 is executed;


if the condition is false, statement2 is executed

• One or the other will be executed, but not both

1-96
Block Statements

• Several statements can be grouped together into a block statement


delimited by braces
• A block statement can be used wherever a statement is called for in
the Java syntax rules
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}

1-97
The Conditional Operator

• Java has a conditional operator that uses a boolean condition to


determine which of two expressions is evaluated
• Its syntax is:
condition ? expression1 : expression2
• If the condition is true, expression1 is evaluated; if it is false,
expression2 is evaluated
• The value of the entire conditional operator is the value of the
selected expression

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

• In many situations, you might consider two floating point numbers to


be "close enough" even if they aren't exactly equal
1-101
Comparing Characters
• In Unicode, the digit characters (0‐9) are contiguous
and in order
• Likewise, the uppercase letters (A‐Z) and lowercase
letters (a‐z) are contiguous and in order

Characters Unicode Values


0–9 48 through 57
A–Z 65 through 90
a–z 97 through 122

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

• The equals method returns a boolean result

if (name1.equals(name2))
System.out.println ("Same name");

1-103
Comparing Strings

• We cannot use the relational operators to compare strings


• The String class contains a method called compareTo to
determine if one string comes before another
• A call to name1.compareTo(name2)
• returns zero if name1 and name2 are equal (contain the same characters)
• returns a negative value if name1 is less than name2
• returns a positive value if name1 is greater than name2

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;

• If the condition is true, the statement is


executed

• Then the condition is evaluated again, and if it is


still true, the statement is executed again

• The statement is executed repeatedly until the


condition becomes false

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 )

• The statement is executed once initially, and then


the condition is evaluated

• The statement is executed repeatedly until the


condition becomes false

1-109
The do Statement
• An example of a do loop:
int count = 0;
do
{
count++;
System.out.println (count);
} while (count < 5);

• The body of a do loop executes at least once

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

for ( initialization ; condition ; increment )


statement;

The increment portion is executed at


the end of each iteration

1-111
The for Statement
• An example of a for loop:
for (int count=1; count <= 5; count++)
System.out.println (count);

• The initialization section can be used to declare a


variable

• Like a while loop, the condition of a for loop is


tested prior to executing the loop body

• The body of a for loop will execute zero or more


times

1-112
The for Statement
• The increment section can perform any calculation
for (int num=100; num > 0; num -= 5)
System.out.println (num);

• Use a for loop for executing statements a specific


number of times that can be calculated or
determined in advance

1-113
The for Statement

• Each expression in the header of a for loop is optional


• If the initialization is left out, no initialization is performed
• If the condition is left out, it is always considered to be true, and
therefore creates an infinite loop
• If the increment is left out, no increment operation is performed

1-114
Determining Event Sources

• Interactive GUIs require establishing a relationship between


components and the listeners that respond to component events
• One listener object can be used to listen to two different components
• The source of the event can be determined by using the getSource
method of the event passed to the listener

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

• A group of radio buttons represents a set of mutually exclusive


options – only one can be selected at any given time
• When a radio button from a group is selected, the button that is
currently "on" in the group is automatically toggled off
• To define the group of radio buttons that will work together, each
radio button is added to a ButtonGroup object
• A radio button generates an action event

1-118

You might also like