Review for Final Exam - University of North Carolina at Chapel Hill

advertisement
COMP 14
Introduction to Programming
Adrian Ilie
Summer Session II, 2005
MTWRF 9:45-11:15 am
Sitterson Hall 011
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Grades
•
•
•
•
•
2
Assignments (7)
Quizzes (3)
Midterm
Final/Project
Class participation
Adrian Ilie
45%
10%
15%
25%
5%
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Exams
• Midterm
♦ to take a make-up midterm, you must
notify me in advance or have a doctor's
excuse
• Final
♦ to take the exam at a different time, you
must get permission from your Dean and
bring me the blue slip you get from the
Dean
3
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Hardware vs. Software
A computer is made up of hardware and software
Software
Hardware
• CPU
- ex: 2 GHz Pentium IV
• input/output
- keyboard
- monitor
- network card
• main memory
- ex: 256 MB RAM
• secondary memory
- ex: 20 GB hard drive
4
Adrian Ilie
• operating systems
- Windows XP
- Mac OS X
• applications
- games
- Microsoft Word
- Internet Explorer
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Hardware Organization
CPU
memory
motherboard
hard drive
5
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Central Processing Unit
• Control Unit (CU)
♦ "the brain" of the CPU
• Program Counter (PC)
♦ points to the next instruction to be executed
• Instruction Register (IR)
♦ holds the currently executing instruction
• Arithmetic Logic Unit (ALU)
♦ carries out all arithmetic and logical ops
• Accumulator (ACC)
♦ holds the results of the operations performed by
the ALU
6
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Main Memory
• Ordered sequence of cells
• AKA Random Access Memory (RAM)
• Directly connected to the CPU
• All programs must be brought into main
memory before execution
• When power is turned off, everything in
main memory is lost
7
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Secondary Storage
• Provides permanent storage for
information
• Retains information even when power is
off
• Examples of secondary storage:
♦
♦
♦
♦
♦
8
Hard Disks
Floppy Disks
ZIP Disks
CD-ROMs
Tapes
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Input Devices
• Definition: devices that feed data
and computer programs into
computers
• Examples:
♦ Keyboard
♦ Mouse
♦ Secondary Storage
9
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Output Devices
• Definition: devices that the
computer uses to display results
• Examples:
♦ Printer
♦ Monitor
♦ Secondary Storage
10
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Input/Output Devices
I/O devices facilitate
user interaction
11
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Hardware Components
12
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Opening MS Word
• Use the mouse to select
MS Word
• The CPU requests the
MS Word application
• MS Word is loaded from
the hard drive to main
memory
• The CPU reads
instructions from main
memory and executes
them one at a time
• MS Word is displayed
on your monitor
13
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Software Categories
• Operating System
♦ controls all machine activities
♦ provides the user interface to the computer
♦ first program to load when a computer is turned
on
♦ manages computer resources, such as the CPU,
memory, and hard drive
♦ examples: Windows XP, Linux, Mac OS X
• Application
♦ generic term for any other kind of software
♦ examples: word processors, missile control
systems, games
14
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Operating System (OS)
• OS monitors overall activity of
the computer and provides
services
• Written using programming
language
• Example services:
♦ memory management
♦ input/output
♦ storage management
15
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Application Programs
• Written using programming
languages
• Perform a specific task
• Run by the OS
• Example programs:
♦ Word Processors
♦ Spreadsheets
♦ Games
16
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Binary Numbers
• N bits to represent 2N values
• N bits represent values 0 to 2N-1
• Example: 5 bits
♦ 32 unique values (0-31)
♦ 000002 = 010
♦ 111112 = 3110
24 23 2 2 21 20
16 + 8 + 4 + 2 + 1 = 31
17
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Converting Decimal to Binary
• Let’s convert 114 to binary
• Repeatedly divide by 2 and write down the
remainder:
114/2=57
57/2=28
28/2=14
14/2=7
7/2=3
3/2=1
1/2=0
remainder
remainder
remainder
remainder
remainder
remainder
remainder
0
1
0
0
1
1
1
• Write the remainders in reverse order:
11100102=11410
• Proof – rewrite and add the equations above:
114=(((((((1*2)+1)*2+1)*2+0)*2+0)*2+1)*2+0)=
=1*26+1*25+1*24+0*23+0*22+1*21+0*20
18
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Programming Languages
• High-level languages make programming
easier
• Closer to spoken languages
• Examples:
♦
♦
♦
♦
♦
19
Basic
FORTRAN
COBOL
C/C++
Java
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Java and Machine Language
To run a Java program:
1. Java instructions need to be
translated into an intermediate
language called bytecode.
2. The bytecode is interpreted into a
particular machine language.
20
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Compiler
•
Compiler: A program that translates a
program written in a high-level
language into the equivalent machine
language.
♦
•
21
(In the case of Java, this machine language is the
bytecode.)
Java Virtual Machine (JVM): A
hypothetical computer developed to
make Java programs machine
independent.
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Processing a Java Program
• Program: written in
Java using the Editor
and compiled to
Bytecode using the
Compiler.
• Loader: transfers the
compiled code
(bytecode) into main
memory and loads the
necessary Libraries.
• Interpreter: reads and
translates each
bytecode instruction
into machine language
and then executes it.
22
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Problem Solving
• The purpose of writing a program is to solve
a problem
• The general steps in problem solving are:
♦
♦
♦
♦
♦
♦
23
understand the problem
dissect the problem into manageable pieces
design a solution
consider alternatives to the solution and refine it
implement the solution
test the solution and fix any problems that exist
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Algorithm
• Sequence of instructions used to carry
out a task or solve a problem
• May be written in either English or
pseudocode
♦ outline of a program that could be translated into
actual code
• May need refinement as you work
Always write out your algorithm before you
begin programming
24
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Problem-Analysis-Coding-Execution
most important step
without
computer
with
computer
25
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Algorithm Design Example
Problem: Convert change in cents to number of halfdollars, quarters, dimes, nickels, and pennies to be
returned.
Example:
♦ given 646 cents
♦ number of half-dollars: divide 646 by 50
• quotient is 12 (number of half-dollars)
• remainder is 46 (change left over)
♦ number of quarters: divide 46 by 25
• quotient is 1 (number of quarters)
• remainder is 21 (change left over)
♦ number of dimes, nickels, pennies
♦ result: 12 half-dollars, 1 quarter, 2 dimes, 0 nickels, 1
penny
26
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Resulting Algorithm
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
27
Get the change in cents
Find the number of half-dollars
Calculate the remaining change
Find the number of quarters
Calculate the remaining change
Find the number of dimes
Calculate the remaining change
Find the number of nickels
Calculate the remaining change
The remaining change is the number of
pennies.
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Programming Languages
• Programming languages have rules of
grammar just as English does
• syntax rules - which statements are legal and
which are not
• semantic rules - determine the meaning of the
instructions
• token - smallest individual unit of a program
♦ special symbols
♦ word symbols
♦ identifiers
28
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Special Symbols
29
+
-
*
/
.
;
?
,
<=
!=
==
>=
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Word Symbols
aka reserved words, or keywords
•
•
•
•
int
float
double
char
•
•
•
•
•
void
public
static
throws
return
• reserved words are always all lowercase
• each word symbol is considered to be a single symbol
• cannot be used for anything other than their intended
purpose in a program
• shown in blue typewriter font in textbook
• full table in Appendix A
30
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Identifiers
• Names of things (variables, constants,
methods) in your programs
• Can be composed of any combination
of letters, digits, underscore (_), and
dollar sign ($)
• Cannot begin with a digit
• May be any length
• Java is case-sensitive
♦ Total, total, and TOTAL are different identifiers
31
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Primitive Data Types
• 8 primitive data types in Java
♦ 4 represent integers
• byte, short, int, long
♦ 2 represent floating point numbers
• float, double
♦ 1 represents characters
• char
♦ 1 represents boolean values
• boolean
32
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Arithmetic Expressions
• Expression - a combination of one or more
operands and their operators
• Arithmetic expressions compute numeric
results and make use of the arithmetic
operators:
Addition
+
Subtraction
Multiplication
*
Division
/
Remainder
%
• If either or both operands associated with an
arithmetic operator are floating point, the
result is a floating point
33
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Operator Precedence
•
Determines the order in which
operators are evaluated:
1. multiplication, division, and remainder
2. addition, subtraction, and string concatenation
3. arithmetic operators with the same precedence
are evaluated from left to right
•
34
Parentheses can be used to force the
evaluation order (just like in math)
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Type Conversion (Casting)
• Used to avoid implicit type coercion
• Syntax
(dataTypeName) expression
• Expression evaluated first, then type
converted to dataTypeName
• Examples:
(int) (7.9 + 6.7) = 14
(int) (7.9) + (int)(6.7) = 13
35
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The class String
• String
♦
♦
♦
♦
♦
sequence of zero or more characters
enclosed in double quotation marks
null or empty strings have no characters
numeric strings consist of integers or decimal numbers
length is the number of characters in a string
• The class String is used to manipulate
strings
• Examples:
♦
♦
♦
♦
36
"Hello World"
"1234"
"45.67"
""
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Strings
• Every character has a position in
the string (starting with 0)
"Hello World"
0123456789...
• The length of the string is the
number of characters in it
♦ what's the length of "Hello World"?
11 (count the space)
37
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Parsing Numeric Strings
• In Java, input from the user
comes in the form of a string
♦ we need to know how to get the number
values out of the string
• Numeric String
♦ a string with only integers or decimal
numbers
♦ "6723", "-823", "345.76"
38
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Variables
• Associated with data
♦ Input data
♦ Output data
♦ Intermediate data
• We need to define:
♦ Data type
♦ Identifier
• Values will be assigned in
expressions
39
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Variables - Steps
1. Identify all data from the algorithm
2. Determine data types (based on the
range and nature of the values)
3. Find meaningful names
•
40
Example: Ch. 1, Exercise 10.
Compute average score.
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Declaration of Variables
dataType identifier;
• Must be declared before it can be used
• Can be (but doesn't have to be) initialized
when declared
• Identifier should start in lowercase, indicate
separate words with uppercase (good style)
• Example:
♦ number of students in class
int numStudents;
• Multiple variables (of the same data type)
can be declared on a single line
int numStudents, numGrades, total;
41
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Assignment
variable = expresssion;
• Assignment Operator (=)
• expression can be a value (3) or a
mathematical expression (2 + 1)
• The expression must evaluate to the
same data type as the variable was
declared
42
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Named Constant
static final dataType IDENTIFIER = value;
• Declared by using the reserved word final
• Always initialized when it is declared
• Identifier should be in ALL CAPS, separate
words with underscore (_) (good style)
• Example:
♦ 1 inch is always 2.54 centimeters
final double CM_PER_INCH = 2.54;
43
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Input
•
Standard input
BufferedReader keyboard = new BufferedReader (new
InputStreamReader (System.in));
String line = keyboard.readLine();
•
Dialog windows
str = JOptionPane.showInputDialog(strExpression);
•
File
BufferedReader inFile = new BufferedReader (new
FileReader (file));
String line = inFile.readLine();
inFile.close();
44
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Output
•
Standard output
System.out.print<ln>(string)
•
Dialog boxes
JOptionPane.showMessageDialog(parentComponent,
strExpression,boxTitleString,messageType);
•
File
String file = "outfile.dat";
PrintWriter outFile = new PrintWriter
(new FileWriter (file));
outFile.print ("Hi");
outFile.println(" There!");
outFile.close();
45
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Writing a Whole Program
• Class - used to group a set of related
operations (methods), allows users to
create their own data types
• Method - set of instructions designed
to accomplish a specific task
• Package - collection of related classes
• Library - collection of packages
46
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Class Libraries
• A collection of classes that we can use
when developing programs
• The Java standard class library is part
of any Java development environment
• The System class and the String class
are part of the Java standard class
library
47
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Packages
• The classes of the Java standard class
library are organized into packages.
• Some of the packages in the standard class
library are:
48
Package
Purpose
java.lang
java.applet
java.awt
javax.swing
java.net
java.util
javax.xml.parsers
General support
Creating applets for the web
Graphics and graphical user interfaces
Additional graphics capabilities and components
Network communication
Utilities
XML document processing
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Using Packages
We need to import some of the
packages we want to use
♦ java.io for BufferedReader
import packageName;
♦ import java.io.*;
• imports all of the classes in the java.io package
♦ import java.io.BufferedReader;
• imports only the BufferedReader class from the
java.io package
49
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Using Predefined Classes
and Methods
• To use a method you must know:
♦ Name of class containing method (Math)
♦ Name of package containing class
(java.lang)
♦ Name of method (round), its parameters
(double a), what it returns (long), and
function (rounds a to the nearest integer)
• See Appendix E for more Java
predefined classes
50
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Creating a Java Program
• Java application program - collection
of one or more classes
♦ every application must have at least one class
• Class
♦ basic unit of a Java program
♦ collection of methods and data members
• Method - set of instructions designed
to accomplish a specific task
♦ print, readLine
51
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Programming in Java
• Java programming language
♦ object-oriented approach to problem
solving
• In the Java programming
language:
♦ a program is made up of one or more
classes
♦ a class contains one or more methods
♦ a method contains program statements
52
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Creating a Java Program
• All Java application programs must
have a method called main
♦ there can be only one main method in any Java
application program
• Most of the time, our programs will
have only one class
• Name of source file must be
ClassNameWithMain.java
53
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Throws Clause
• throws clause - exceptions thrown by
the main method
• exception - occurrence of an
undesirable situation that can be
detected during program execution
♦ can either be handled or thrown
• readLine throws the exception
IOException
• We won't handle the exception, we'll
just throw it
54
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Import Statements
• Tell the compiler which packages are
used in the program
• Import statements and program
statements constitute the source code
• Source code saved in a file with the
extension .java
• Source code file must have the same
name as the class with the main
method
55
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The main method
• Heading
public static void main (String[] args)
throws IOException
• Body
♦ statements enclosed by { }
♦ declaration statements
• used to declare things such as variables
♦ executable statements
• perform calculations, manipulate data, create
output, accept input, etc.
56
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Skeleton
import statements if any
public class ClassName
{
declare named constants and/or stream objects
public static void main (String[] args)
throws IOException
{
variable declarations
executable statements
}
}
57
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Style
• Syntax
♦ beware! a syntax error in one place might lead to
syntax errors in several other places
• Use of semicolons, braces, commas
♦ all Java statements end with semicolon
♦ braces {} enclose the body of a method and set it
off from other parts of the program (also have
other uses)
♦ commas separate list items
58
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Style
• Semantics
♦ set of rules that gives meaning to a language
♦ beware! the compiler will not be able to tell you
about semantic errors (example: missing
parentheses in mathematical expression)
• Documentation
♦ comments
♦ naming rules
• use meaningful identifiers
♦ prompt lines
• let the user know what type of input is expected
59
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Style and White Space
• White space
♦
♦
♦
♦
blanks, tabs, blank lines
used to separate words and symbols
extra space is ignored by computer
blank line between variable declaration and rest
of code
• Programs should be formatted to
enhance readability, using consistent
indentation
60
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Comments
• Not used by the computer
♦ only for human consumption
• Used to help others understand code
♦ explain and show steps in algorithm
♦ comments are essential!
• Should be well-written and clear
• Comment while coding
• Also called inline documentation
61
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Java Comments
// this is a one-line comment
♦ “comments out” the rest of the line after
marker //
/* this is a multi-line
comment */
♦ “comments out” everything between
markers /* and */
62
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Classes
• What is a class?
♦ Data
♦ Operations
• Classes allow creation of new
data types
public class Student
{
}
63
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Classes Vs. Data Types
Abstract
Descriptors
♦ Data Type
Concrete Entities
♦ Variable
♦ Object
♦ Class
64
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Inside a class
• Other classes
• Data types
• Methods (operations)
public class Student
{
private String name;
private int age;
public void ComputeGrade();
}
65
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Primitive Variables
int x = 45;
• x is associated with a memory location. It
stores the value 45
• When the computer sees x, it knows which
memory location to look up the value in
66
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Reference Variables
Integer num;
• The memory location associated with
num can store a memory address.
• The computer will read the address in
num and look up an Integer object in
that memory location
67
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Creating Objects
• We use the new operator to create
objects, called instantiation
parameter
Integer num;
num = new Integer(78);
68
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Changing the Reference Var
num = new Integer (50);
• The address of the newly-created
object is stored in the already-created
reference variable num
69
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Garbage Collection
• What happened to the memory space
that held the value 78?
• If no other reference variable points
to that object, Java will "throw it
away"
70
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Using Objects
object
• System.out
♦ represents a destination to which we can
send output
• Example:
♦ println
method
System.out.println (”Hello World!”);
object
method
dot operator
71
Adrian Ilie
information provided to
the method
(parameters)
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The class String
• String variables are reference
variables
• Given String name;
♦ Equivalent Statements:
name = new String(“Van Helsing”);
name = “Van Helsing”;
72
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
name = “Van Helsing”;
Van Helsing
Van Helsing
Van Helsing
73
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The class String
• The String object is an instance of class
string
• The value “Van Helsing” is instantiated
• The address of the value is stored in name
• The new operator is unnecessary when
instantiating Java strings
• String methods are called using the dot
operator
74
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Common String Methods
• String(String str)
♦ constructor
♦ creates and initializes the object
• char charAt(int index)
♦ returns char at the position specified by index (starts
at 0)
• int indexOf(char ch)
♦ returns the index of the first occurrence of ch
• int compareTo(String str)
♦ returns negative if this string is less than str
♦ returns 0 if this string is the same as str
♦ returns positive if this string is greater than str
75
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Common String Methods
• boolean equals(String str)
♦ returns true if this string equals str
• int length()
♦ returns the length of the string
• String replace(char toBeReplaced,
char replacedWith)
♦ returns the string in which every occurrence of toBeReplaced
is replaced with replacedWith
• String toLowerCase()
♦ returns the string that is the the same as this string, but all
lower case
• String toUpperCase()
♦ returns the string that is the same as this string, but all upper
case
76
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The StringTokenizer Class
• tokens
♦ elements that comprise a string
• tokenizing
♦ process of extracting these elements
• delimiters
♦ characters that separate one token from another
• StringTokenizer class
♦ defined in the java.util package
♦ used to separate a string into tokens
77
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The StringTokenizer Class
• Default delimiters:
♦ space, tab, carriage return, new line
• Methods
♦
♦
♦
♦
♦
78
StringTokenizer (String str)
StringTokenizer (String str, String delimits)
String nextToken()
boolean hasMoreTokens()
int countTokens()
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
class DecimalFormat
• Import package java.text
• Create DecimalFormat object and initialize
DecimalFormat fmt = new DecimalFormat (formatString);
• FormatString
♦ "0.00" - limit to 2 decimal places, use 0 if there's no item
in that position
♦ "0.##" - limit to 2 decimal places, no trailing 0
• Use method format
♦ rounds the number instead of truncating
• Result of using DecimalFormat is a String
79
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Control Structures
Three methods of processing a
program:
1. In sequence
♦
statements are executed one after another in
order
2. Branching
♦
altering the flow of program execution by
making a selection or choice
3. Looping
♦
80
altering the flow of program execution by
repetition of statement(s)
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Flow of Execution
81
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Relational Operators
• Relational Operator
♦ allows you to make comparisons in a program
♦ binary operator
• needs two operands
• Condition is represented by a logical
(Boolean) expression
♦ expression that has a value of either true or false
82
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Relational Operators
• Less than
• Greater than
• Equal to
<
>
==
♦ not assignment ‘=‘
• Not equal to
!=
• Less than or equal to
<=
• Greater than or equal to >=
83
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Comparing Characters
• In Java, characters are ordered according to the
Unicode / ASCII character set (pg. 855)
• ‘a’ comes before ‘b’ in the character set, so we
can say ‘a’ < ‘b’
• Order
♦
♦
♦
♦
space character (' ')
digits (‘0’, ‘1’, …)
uppercase
lowercase
• Application: sort alphabetically
84
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Comparing Floating-Point
• Be careful when using the equality
(==) to compare floating point
numbers
• Every bit in the representation must
be equal
♦ computer can only store a certain number of digits
after the decimal
• If the numbers are results of
computation, it’s unlikely that two
floating point numbers will be exactly
equal
85
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Comparing Strings
• Strings are compared on a characterby-character basis
♦ first character not in common determines how the
strings compare
♦ ex: "Airplane" is less than "Airport"
• If two strings have different lengths,
and one is a substring of the other,
the shorter one is evaluated as less
♦ ex: "Air" is less than "Airplane"
86
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Comparing Strings
Don't use relational operators (==, <, >)
parameter
for Strings
method
str1.compareTo (str2)
Returns an integer value:
♦ < 0 if str1 is less than str2
♦ 0 if str1 is equal to str2
♦ >0 if str1 is greater than str2
str1.equals (str2)
Returns a boolean value of true or false
87
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Boolean Operators
• NOT
!
(unary)
true
(binary)
false
!(2+2==5)
• AND
&&
(2+2==5) && (1+1==2)
• OR
||
(binary)
(2+2==5) || (1+1==2)
88
Adrian Ilie
true
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Short Circuited Operators
• The processing of logical AND (&&)
and logical OR (||) is “shortcircuited”
• If the left operand is sufficient to
determine the result, the right
operand is not evaluated
count != 0 && (total/count > MAX)
89
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Precedence of Operators
90
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The if Statement
The condition must be a boolean expression.
It must evaluate to either true or false.
if is a Java
reserved word
if ( condition )
statement;
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
91
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The 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
92
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Nested if Statements
The general syntax of a nested if statement is:
if (condition1)
{
block1
}
else if (condition2)
{
block2
}
else
{
block3
}
93
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The switch Statement
• The general syntax of a switch statement
is:
switch
and
case
are
reserved
words
94
Adrian Ilie
switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
If expression
matches value2,
control jumps
to here
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The switch Statement
• Expression evaluated must be integral
type
♦ integer or character, not boolean or floating point
• Case values must be constant
(literal), not variable
• Can be implemented with nested if
statements, but is much clearer with
switch statements
95
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The switch Statement
• default
♦ no case value matches the expression
♦ if no default exists and no case value
matches the expression, no statements in
the switch statement are executed
• break
♦ processing jumps to statement following
the switch statement
♦ usually at the end of each case
96
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Writing Selection Statements
What Type of Construct To Use?
• Only need to execute additional statements
if condition is true
if
• Need to execute separate additional
statements based on if the condition is true
or false
if-else
• Need to execute different statements based
on multiple conditions
nested if-else
• Need to execute different statements based
on an expression that evaluates to a char or
int
switch
97
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Writing Selection Statements
• Write the outline of the selection
statement
♦ keywords
♦ curly braces
♦ case and break statements (for switch)
• Write the expression
♦ boolean expression, or condition
♦ expression or variable evaluating to char or int
• Write statements that execute based on
the condition
98
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Repetition Statements
• Allow us to execute a statement
multiple times
• Often referred to as loops
• Controlled by boolean expressions
♦ like selection, or conditional, statements
• Java has three kinds of repetition
statements:
♦ the while loop
♦ the for loop
♦ the do loop
99
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Loops
• Must use a loop control variable
♦ controls how many times to loop
• 4 Parts to Every Loop
♦ initialization - set loop control variable
before condition
♦ condition - when to stop
♦ update - change the loop control variable
♦ body - actions to repeat
100
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Typical Uses of Loops
• Repeat a section of code a specified number
of times - counter-controlled
• Repeat a section of code (reading input) until
a specific value is read - sentinel-controlled
• Repeat a section of code (reading input) until
a valid value is entered - input validation
• Repeat a section of code (reading from a file)
until the end of the file is reached - EOF-
controlled
• Repeat a section of code until a boolean
variable becomes false - flag-controlled
101
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The while Loop
Syntax
while is a
reserved word
while ( condition )
{
loop body;
}
If the condition is true, the loop body is executed.
Then the condition is evaluated again.
The loop body is executed repeatedly until
the condition becomes false.
102
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The while Loop
• Syntax
while (expression)
statement
• Expression is always
true in an infinite loop
• Statements must
change value of
expression to false
103
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Counter-Controlled while Loop
• Used when we know exactly the number of
times to execute the loop
• Basic Form:
counter = 0;
while (counter < N)
{
...
counter++;
N is the
number
of times the
loop should
execute
...
}
104
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Sentinel-Controlled while Loop
• Used when exact number of entry
pieces is unknown but last entry
(special / sentinel value) is known
• Basic Form:
input the first data item into variable
while (variable != sentinel)
{
...
input a data item into variable
}
105
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Input Validation while Loop
• Used to ensure that the user enters
valid input
• Basic Form:
input a data item into variable
while (variable is not in valid range)
{
ask the user for valid input
input a data item into variable
}
106
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Flag-Controlled while Loop
• Boolean value used to control loop
• Basic Form:
boolean found = false;
while (!found)
{
...
if(expression)
found = true;
...
}
107
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
EOF-Controlled while Loop
• Used when input is from a file
• Sentinel value is not always
appropriate
• Basic Form:
inputLine = inFile.readLine();
while (inputLine != null)
{
null is a reserved word
...
inputLine = inFile.readLine();
}
108
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The for Loop
• Specialized form of while loop
• Simplifies the writing of count-controlled
loops
Basic Form:
for (initialization; condition; update)
{
statement(s);
}
109
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The for Loop
Execution
1. initial statement
executes
2. loop condition
evaluated
3. If loop condition
evaluates to true,
execute for loop
statement and
execute update
statement
4. Go back to step 2
and repeat until
loop condition is
false
110
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The for Loop
Syntax
Reserved
word
The initialization
is executed once
before the loop begins
The loop body is
executed until the
condition becomes false
for ( initialization; condition; update )
{
loop body;
}
The update portion is executed at the end of each iteration
The condition-loop body-update cycle is executed repeatedly
111
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
for vs. while
A for loop is functionally
equivalent to the following while
loop structure:
initialization;
while ( condition )
{
loop body;
update;
}
112
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Comparing while and for
While Loop
For Loop
final int LIMIT=3;
int i = 0;
final int LIMIT=3;
int i;
while (i < LIMIT)
{
System.out.println (i);
i++;
}
for (i=0; i<LIMIT; i++)
{
System.out.println (i);
}
System.out.println
(“All done!”);
System.out.println
("All done!");
113
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Watch out!
• for statement ending in semicolon
is empty; does not affect program
for (count=0; count<LIMIT; count++);
• while statement ending in
semicolon results in infinite loop
while (count<LIMIT);
114
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The do...while Loop
Syntax
do
{
do and
while are
reserved
words
loop body;
}
while ( condition );
The loop body is executed once initially,
and then the condition is evaluated
The loop body is executed repeatedly
until the condition becomes false
115
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
do…while Loop
(Post-test Loop)
do {
statement(s);
} while (expression);
116
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The do...while Loop
• Like a while loop, but its
condition is at the end of the loop
• Loop body always executes at least
once
• Must also be checked for
termination (not an infinite loop)
• Anything you can do with a
do...while loop, you can do
with a while loop
117
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Comparing while and
do...while
while Loop
do...while Loop
final int LIMIT=3;
int count = 0;
final int LIMIT=3;
int count = 0;
while (count < LIMIT)
{
System.out.println
(count);
count++;
}
do
{
System.out.println
(“All done!”);
118
Adrian Ilie
System.out.println
(count);
count++;
}
while (count < LIMIT);
System.out.println
("All done!");
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
break Statements
• Used to exit early from a loop
• Used to skip remainder of switch
structure
• Can be placed within if
statement of a loop
♦ If condition is met, loop exited
immediately
119
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
continue Statements
• Used in while, for, and do...while
structures
• When executed in a loop, the remaining
statements in the loop are skipped;
proceeds with the next iteration of the
loop
• When executed in a while/do…while
structure, expression evaluated
immediately after continue statement
• In a for structure, the update
statement is executed after the
continue statement; then the loop
condition executes
120
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Nested Control Structures
• Provides new power, subtlety,
and complexity
• if, if…else, and switch
structures can be placed within
while loops
• for loops can be found within
other for loops
♦ each time through the outer loop, the
inner loop goes through its full set of
iterations
121
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Object-Oriented Design
• What is it?
Designing a solution to a problem
by first identifying components
called objects, and determining
how the objects interact with each
other
122
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Objects
VCR Example
• Use it without knowing how it's made
• Internal parts are hidden -- only
interact with the provided buttons
• Can't modify the functions of a VCR -record button always records, play
button always plays
Same is true for objects (like Strings) that are
provided by Java
123
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Objects
Consist of data and operations on the data
• Data - descriptive characteristics
• Operations - what it can do (or what can be done
to it)
Example
A coin that can be flipped so that its face shows
either "heads" or "tails"
♦ data: its current face (heads or tails)
♦ operations: it can be flipped
Operations can change data.
124
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Objects
And Methods and Classes
• We represent operations with methods
♦ group of statements that are given a name
• We can use objects and their methods
without knowing exactly how the methods
work
• An object is an instance of a class. A class is
the blueprint of an object.
♦ the class provides the methods that can operate on an
object of that class
125
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Classes
• A class contains data declarations and
method declarations
• A class is a description of an object
♦ just a model, not an actual object
♦ you can think of the concept of a book without
thinking of a particular book
• A class is no more an object than a
blueprint is an actual house
126
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Object-Oriented Design
Simplified Methodology
1. Write down detailed description of
problem
2. Identify all (relevant) nouns and verbs
3. From list of nouns, select objects
4. Identify data components of each object
5. From list of verbs, select operations
127
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Anatomy of a Class
• A class contains data declarations
and method declarations
int width;
int length;
Data declarations
Method declarations
(operations)
128
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Classes and Objects
A class
(the concept)
An object
(the realization)
length = 15, width = 3
Rectangle
length = 20, width = 6
Multiple objects
from the same class
129
Adrian Ilie
length = 15, width = 15
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Why Use Methods?
• To divide complex programs into
manageable pieces
• Abstraction
♦ provide an operation to be performed on an object
(ex: computeArea)
• Code Re-use
♦ write a small piece of code that can be used
(called) multiple times (saves typing)
130
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Methods
• Pre-defined methods
♦
♦
♦
♦
provided by Java standard library
we've used these before
Math class (Math.pow, Math.sqrt, ...)
Integer class (Integer.parseInt, ...)
• User-defined methods
♦ you write these
131
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Method as a Black Box
Input parameters
METHOD
Return value
Internal data members
of the class
• A method can use input parameters and
internal data members of the class
• It may modify the value of internal data
members
• It may also return a value
132
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Control Flow
• Program control flow
♦ execution always begins with the first statement
in the method main
♦ other methods execute only when called
• Method control flow
♦ when a method is invoked, the flow of control
jumps to the method and the computer executes
its code
♦ when complete, the flow of control returns to the
place where the method was called and the
computer continues executing code
• Test this with the debugger!
133
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Using Methods
What You Need To Know
1.
2.
3.
4.
Name of the method
Number of parameters
Data type of each parameter
Data type of value computed
(returned) by the method
5. The code required to
accomplish the task
134
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Method Declaration
• Specifies the code that will be
executed when the method is
invoked (or called)
• Located inside a class definition
• Contains
♦ method header
♦ method body
135
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Method Header
A method declaration begins with a method header
public static int countCharInWord (char ch, String word)
visibility
modifiers
return
type
method
name
formal parameter list
The parameter list specifies the type
and name of each parameter
The name of a parameter in the method
declaration is called a formal parameter
136
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Return Value
• Value-returning methods
♦ The method returns the result of some
operations
♦ Like mathematical functions
♦ Return one single value
• Void methods
♦ Perform operations but return no value
137
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Value-Returning Methods
• Think mathematical function
f(x) = 2x + 5
f(x, y) = 2x + y
f(1) = 7
f(2) = 9
f(3) = 11
f(1, 5) = 7
f(2, 3) = 7
f(3, 1) = 7
• Can have multiple arguments
(parameters)
• Only one result of the function
138
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Value-Returning Methods
Uses
• Save the value for future calculation
• Use the value in a calculation
• Print the value
x = Math.pow (y, 2);
z = a + Math.pow (y, 2) + x;
System.out.println (Math.pow (y, 2));
139
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Return Type
• Indicates the type of value that the
method evaluates to:
♦ primitive data type
♦ class name
♦ void  reserved word indicating that nothing is
returned
• When a value is returned, the method
call is replaced with the returned value
int number = countCharInWord ('e', "Heels");
2
140
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The return Statement
• Tells the computer to "return" back to
where the call was originally made.
• Specifies the value that will be returned
return expression;
• The data type of expression must match
the method's return type
• Methods with return types of void usually
don't (but can) have a return statement
• Value-returning methods must have at least
one return statement
141
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Void Methods
• Do not return a value
• Have a return type of void
• Similar in structure to valuereturning methods
• Call to method is always a standalone statement
• Can use return statement to exit
method early
142
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The main Method
The main method looks just like
all other methods
public static void main (String[] args)
modifiers
143
Adrian Ilie
return method
type
name
parameter
list
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Method Body
The method header is followed by the method body
public static int countCharInWord (char ch, String word)
{
int count = 0;
for (int i = 0; i<word.length(); i++) {
if (word.charAt(i) == ch) {
count++;
}
}
ch and word are local data
return count;
}
They are created each time the
method is called, and are
destroyed when it finishes
The return expression must be
executing
consistent with the return type
144
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Parameters
Each time a method is called, the actual parameters in the
call are copied into the formal parameters
int num = countCharInWord ('e', "Heels");
public static int countCharInWord (char ch, String word)
{
int count = 0;
for (int i = 0; i<word.length(); i++) {
if (word.charAt(i) == ch) {
count++;
}
}
return count;
}
145
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Parameters
• Formal parameters
♦ variable declarations in the method header
♦ automatic local variables for the method
• Actual parameters
♦ actual values that are passed to the method
♦ can be variables, literals, or expressions
printStars (35);
printStars (30 + 5);
int num = 35;
printStars (num);
146
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Parameters
Primitive Data Type Variables
• If a formal parameter is a variable of a
primitive data type, can it be modified
inside a method?
♦ The value from the actual parameter is
copied
♦ There is no connection between variables
inside the method and outside
♦ Conclusion: it cannot be modified!!
147
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Parameters
Reference Variables
• If a formal parameter is a reference
variable, can the object be modified
inside a method?
♦ The address from the actual parameter is
copied
♦ The local reference variable points to the
same object
♦ Conclusion: it can be modified!!
148
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Primitive Data Types
• What if we want to modify a
variable of a primitive data type
inside a method?
♦ Encapsulate it in a class
♦ Example: IntClass (ch. 6, p. 306/350)
IntClass is a class suggested in the book, but it is
not a built-in class in Java!!!
149
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Overloading Methods
• Overloading - the process of using the same
method name for multiple methods
• The signature of each overloaded method
must be unique
♦ number of parameters
♦ type of the parameters
♦ not the return type of the method, though
• The compiler determines which version of
the method is being invoked by analyzing
the parameters
150
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Constructors
public class Rectangle
{
private int length;
private int width;
Rectangle r2 = new
Rectangle (5, 10);
public Rectangle ()
{
length = 0;
width = 0;
}
151
public Rectangle (int l, int w)
{
length = l;
width = w;
} Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The toString Method
• Special method in Java classes
• Produces a String object based on the
current object, suitable for printing
• Mapped to the '+' operator
• Also called when the object is a
parameter in a print() or println()
method
• There is a default toString method,
but it's better if we write our own
System.out.println(r1);
152
Adrian Ilie
System.out.println(r1.toString());
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The Reference this
• Reserved word
• Refers to instance variables and
methods of a class
• Allows you to distinguish between
member variables and local variables
with the same name
153
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Rectangle.java
public class Rectangle
{
private int length;
private int width;
public Rectangle (int length, int width)
{
this.length = length;
this.width = width;
}
154
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Review Classes and Methods
ReverseString.java
• When do you use dot operator (.)
to access methods?
♦ Must use dot operator to access method
that is in a different class
♦ To access a method in ReverseString from
ReverseTester, use dot operator
♦ To access a method in ReverseString from
ReverseString, NO dot operator
155
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Review Classes and Methods
ReverseString.java
• When do you use public vs.
private?
♦ Use private:
• When the method or data member is only going
to be accessed inside the same class
♦ Use public:
• When the method or data member is going to
be accessed outside the class
• Anything that is called, or used, inside
ReverseTester class must be public
156
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Review Classes and Methods
ReverseString.java
• Why did we not use static in
ReverseString class?
When and why do we use static?
• Do not need object to use method/variable
• Consistent among all objects
• Shared among all objects of the class
157
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Review Classes and Methods
ReverseString.java
• Why did we not use static in
ReverseString class?
When and why do we use static?
• Want all objects of class to share one copy of data
• Do not need method/variable to be object specific
NOTE:
• Can't call a non-static method from a static method
• Can't access non-static variables from a static
method
158
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Review Classes and Methods
ReverseString.java
• Why was there no main method in
ReverseString class?
♦ Only a driver class (a class that tests your
program) has a main method
♦ General rule:
• For each program you write, there will only be one
main method
• Here, it was given in ReverseTester class
159
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Communication between
Classes
• Methods provide communication
between methods
♦ Parameters provide input into class
♦ Return value provides output
public returnType methodName ( formal parameters )
Output from method
160
Adrian Ilie
Input to method
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Arrays
• An array is a list of values that can be
represented by one variable
• Members of an array must all have
the same data type
• Each value is stored at a specific,
numbered position in the array
♦ the number corresponding to each position is
called an index or subscript
• All arrays have a length
♦ number of elements the array can hold
161
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Review
0
1
2
3
Arrays
• Declaration
can use variables and
expressions as initial values
int[] counts;
• Instantiation
counts = new int[50];
• Initialization / Access
for (int i=0; i<counts.length; i++) {
counts[i] = 0;
}
• Initializer List
♦ declaration, instantiation, and initialization
double[] grades = {98.7, 72.4, 87.5};
int[] numbers = {num, num+1, num+2, num+3};
162
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Parallel Arrays
Arrays are parallel if
corresponding components hold
related information
String[] studentName;
double[] studentGPA;
For example, studentName and
studentGPA are parallel if
studentGPA[3] is the GPA of the
student with studentName[3].
163
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Copying Arrays
counter
int[] counter = {1, 2, 3, 4, 5};
int[] temp = new int[counter.length];
temp
0
1
2
3
4
164
1
2
3
2
3
2
3
4
4
4
5
5
for (int i=0; i<counter.length; i++) {
temp[i] = counter[i];
}
Adrian Ilie
1
0
1
i
1
4
2
5
0
3
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Arrays as Parameters
• Entire array can be passed as a
parameter
♦ method can change elements of the array
permanently
♦ since we're passing a reference
• Elements of an array can be
passed as parameters, too
♦ normal rules apply…
165
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Arrays as Parameters
• Entire array can be passed as a
parameter
♦ method can change elements of the array
permanently
♦ since we're passing a reference
• Elements of an array can be
passed as parameters, too
♦ normal rules apply…
166
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Arrays of Objects
• Can use arrays to manipulate objects
• Create array of objects
classname[] array = new classname[size];
• Must instantiate each object in array
for(int j=0; j <array.length; j++) {
array[j] = new classname();
}
167
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Binary Search
• Requires ordered (sorted) list
• Set searchRange to the entire list
• Repeat:
♦ pick a “test value” in the middle of searchRange
♦ if test value == value searching for
• Stop!
♦ if test value > value searching for
• searchRange = lower half of searchRange
♦ if test value < value searching for
• searchRange = upper half of searchRange
168
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Example
Looking for 46
Trial 1
2 4 5 12 16 19 22 26 29 32 37 41 46 50
2
2 4 5 12 16 19 22
26 29 32 37 41 46 50
3
2 4 5 12 16 19 22 26
169
Adrian Ilie
29 32 37
41 46 50
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Selection Sort
Methods
• Scan the list to find the smallest value
• Swap that value with the value in the
first position in the list
• Scan rest of list to find the next
smallest value
• Swap that value with the value in the
second
position
in
the
list
loop
• And so on, until you get to the end of
the list
170
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Inheritance
• JFrame is a class provided by the package
javax.swing
• Instead of instantiating an object of the
JFrame class, we're going to extend the
JFrame class (called inheritance).
• The new class "inherits" features (including
methods and variables) from the existing
class -- big time-saver!
• We can use all of the methods and
variables from JFrame, while adding our
own.
171
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Extending JFrame
• Use the modifier extends, which is a
reserved word
public class BigGUI extends JFrame
{
}
• JFrame is the superclass
• BigGUI is the subclass
• It is ok to learn the recipe
172
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Next Step
• We'll need a constructor for BigGUI
♦ set the window title setTitle
♦ set the window size setSize
♦ set the default operation when the close
button is pressed
setDefaultCloseOperation
♦ display the window setVisible(true)
• We'll need a main method
♦ create an object of the BigGUI class (which
will call the constructor)
173
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
import javax.swing.*; // needed for JFrame
public class BigGUI
{
private final
private final
private final
extends JFrame
static String TITLE = “Big GUI";
static int WIDTH = 700;
static int HEIGHT = 600;
public BigGUI() // constructor
{
setTitle(TITLE);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
BigGUI gui = new BigGUI();
}
}
174
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Adding Things
• Access the content pane so we can
add things (buttons, labels, images)
Container content = getContentPane();
♦ Container class is provided by the java.awt
package
♦ add import statement for java.awt
• Then, we set the layout type and add
things to the content pane
175
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Layout Managers
• FlowLayout
♦ default
♦ components are added left to right, top to bottom
• BorderLayout
♦ consists of NORTH, SOUTH, EAST, WEST, CENTER regions
♦ size of CENTER region depends on the number of
components in the EAST and WEST regions
• GridLayout
♦ define number of rows and columns to get equally sized
cells
♦ cells are filled left to right, top to bottom
176
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
BorderLayout
• Select layout for BigGUI as
BorderLayout
content.setLayout(new BorderLayout());
• When adding components with
BorderLayout, you have to specify
the section (using NORTH, SOUTH,
EAST, WEST, CENTER constants from
BorderLayout
class)
content.add(item, BorderLayout.SECTION);
177
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
JLabels
• We'll identify the regions of the
BorderLayout with labels (text areas)
• JLabel is a region of text
♦ can be assigned an alignment (left-justified, rightjustified, centered)
JLabel northLabel = new JLabel ("NORTH",
SwingConstants.CENTER);
JLabel southLabel = new JLabel ("SOUTH");
• Text can be changed with setText
method
northLabel.setText ("Changed Text");
178
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Colors
• Set the background color of the content
pane
• Set the foreground color of the text
(JLabels)
• Use Color class from the java.awt package
• Available colors pg. 734
♦ constants (but lowercase)
• Methods
♦ darker() - darkens the color
♦ brighter() - brightens the color
content.setBackground(Color.blue.darker().darker());
northLabel.setForeground(Color.white);
179
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Adding Images
• We can create images and associate
them with labels
• ImageIcon
♦ use JPG or GIF images
filename
ImageIcon image = new ImageIcon ("img/0.gif");
• Use setIcon method from JLabel
class
centerLabel.setIcon (image);
180
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Text Position Relative to Icon
label.setVerticalTextPosition(vposition);
label.setHorizontalTextPosition(hposition);
SwingConstants.TOP
SwingConstants.CENTER
SwingConstants.BOTTOM
181
Adrian Ilie
SwingConstants.LEFT
SwingConstants.CENTER
SwingConstants.RIGHT
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
BigGUI.java
• Add icon.
182
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
JLabel and JTextField
• Very similar. With JTextField we can
also type data from outside and
access it in the program.
JLabel output=new JLabel();
JTextField input=new JTextField();
…
String inputStr=input.getText();
output.setText(“OUTPUT RESULT”);
183
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Using Buttons
• Create JButton objects
• Buttons generate events when clicked
• Add event handlers
• Inside event handler, code operations
to be executed when button is clicked
184
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Adding Buttons
• To create a button, we use the JButton
class
JButton toLower = new JButton (“To Lower Case");
• Add button to the content pane
content.add(toLower);
• Change text of the button with the setText
method
toLower.setText(“Convert to Lower Case");
• Enable/disable the button with setEnabled
method
toLower.setEnabled(false);
185
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Buttons and Events
• Pressing buttons triggers action
events
• Setup a listener for the event
♦ actionPerformed method from
ActionListener class
♦ ActionListener class from the
java.awt.event package
• something else to import
186
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
ActionListener
• Special type of class, called
interface
• Interface - class that contains
only the method headings (no
method bodies)
public interface ActionListener
{
public void actionPerformed (ActionEvent e);
}
187
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
ActionListener
• In order to handle an event, define a
class that will implement
ActionListener.
private class ButtonHandler implements ActionListener
• Make the class ButtonHandler an
internal class of our main class.
• In ButtonHandler, code the method
actionPerformed
188
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
ActionListener
• Declare a ButtonHandler that will be
a data member of the main class.
private ButtonHandler toLowerHandler;
• Instantiate the ButtonHandler (e.g.
in the constructor)
toLowerHandler=new ButtonHandler();
• Once the JButton object is created,
register the action listener:
toLower.addActionListener(toLowerHandler);
189
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
actionPerformed
• Variables we want to access inside
the actionPerformed methods, must
be declared as member variables of
the main class
♦ not local to constructor
• Make input, output, and the
buttons member variables
190
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Applets
• A Java application is a stand-alone
program with a main method
• A Java applet is a Java program that
is intended to be transported over the
web and executed using a web
browser
♦ an applet doesn't have a main method
♦ needs an extra import statement:
import java.applet.Applet;
191
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Applet Methods
• Several methods from Applet class
that are invoked automatically at
certain points in an applet's life
♦ init - executed only once when the applet is
initially loaded
♦ start - called when applet becomes active (when
browser loads / returns to the page)
♦ stop - called when applet becomes inactive (when
browser leaves the page)
♦ paint - automatically executed and is used to
draw the applets contents
192
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Converting Apps to Applet
• See Ch 13, pgs. 855-858 (745-748)
• Extends JApplet instead of JFrame
• No main method
• No constructor
♦ put code from constructor in init() method
• No setVisible, setTitle, or
setSize methods
193
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Applets and the Web
• An applet is embedded into an HTML file
using a tag that references the bytecode file
(ClassName.class) of the applet class
• It is actually the bytecode version of the
program that is transported across the web
• The applet is executed by a Java interpreter
that is part of the browser
♦ this Java interpreter not included in Windows XP, must
download from java.com
194
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Applets and the Web
• Basic HTML file for an applet:
<html> <body>
<applet code = "ClassName.class">
</applet> </body> </html>
• Can also specify size of applet window
<applet code="ClassName.class"
height=200 width=300> </applet>
• Put the applet HTML file (named
something.html) and your Java applet
bytecode (named ClassName.class) in your
public_html folder in AFS space.
195
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Download