Title: Workshop on Java Programming
1Workshop on Java Programming
- September 29, October 13, October 20
- YANPING CHEN
- ychen_at_site.uottawa.ca
2Introduction to Object-Oriented Programming
Concepts
3Software Life Cycle
- Steps in software development
- Problem specification
- Algorithm development
- Coding
- Testing
- Debugging
- Maintenance
- Documenting is an activity that occurs throughout
the cycle
4Problem Specification
- The goal use computer to solve problems
- Problems are usually stated in natural language
- Software designer extracts the exact problem
specification from the informal problem --
requirements analysis
5Understand the Problem
- Clarify
- What data is given (available for use when the
problem-solving takes place) - What results are required
- What assumptions are safe to make
- What constraints must be obeyed
6Example 1
- Informal statement
- John wants to know the total and average cost of
the three books he just bought. - Givens descriptions and names of the values that
are know - A, B, C numbers representing the cost of each of
Johns books - Results descriptions and names of the values to
be computed from the givens - SUM, the sum of A, B and C
- AVG, the average of A, B, C
7Example 2
- Informal statement
- Write an algorithm that takes four scores (each
out of 25) and computes their average (out of
100) - Givens descriptions and names of the values that
are know - A, B, C, D numbers representing the four scores
- Results descriptions and names of the values to
be computed from the givens - AVG, the average of A, B, C, D out of 100
8Algorithm
- An algorithm is a solution for a problem
- An algorithms HEADER specifies the name of the
algorithm, an order for the givens and an order
for the results - An algorithms BODY is a sequence of instructions
which, when executed, computes the desired
results from the givens. - Algorithms are written in pseudocode. A precise
notation convenient for people but not executable
by computers.
9Intermediate Variables
- Often it is useful within an algorithm to use a
variable that is neither a given nor a result to
temporarily hold a value. - Intermediate variables values are not returned
to the calling statement, nor are they remembered
from one call to the next.
10Algorithm for Example1
- GIVENS numbers A, B, C
- RESULTS
- SUM, the sum of A, B and C
- AVG, the average of A, B and C
- HEADER
- Alg1(A, B, C)
- Return (Sum, Avg)
- BODY
- Sum ABC
- Avg Sum /3
11Algorithm for Example2
- GIVENS numbers A, B, C, D
- RESULTS
- AVG, the average of A, B, C and D out of 100
- HEADER
- Alg2(A, B, C, D)
- Return (Avg)
- BODY
- Sum A B C D //an Intermediate Variable
- Avg Sum /4/25100
12Tracing an Algorithm
- To TRACE an algorithm is to execute it by hand,
one statement at a time, keeping track of the
value of each variable. - The aim is either to see what results the
algorithm produces or to locate bugs in the
algorithm.
13Tracing Example
- Example 1
- Avg Alg1 (18, 25, 20)
- Example 2
- Avg Alg2 (18, 25, 20, 19)
14Invoking an Algorithm
- To invoke an algorithm you use a call statement
which is identical to the header except for the
names of the givens and results. - (X,Y) Alg1(10, 7, -2)
- invokes algorithm Alg1 with givens A10, B7,
C-2 and returns the results in X(Sum) and Y(Avg) - Information is passed between the call statement
and the algorithm based on the ORDER of the
givens and results, not their names.
15Coding
- Coding translating an algorithm into a
particular programming language so it can be
executed on a computer - Be sure your algorithm is correct before coding
it by tracing it on test data. - Coding is largely a mechanical process, not a
creative one. - Both algorithm development and coding require
very careful attention to detail
16Translating to Code
- To program is to first develop and test
algorithms in pseudocode and then TRANSLATE them
into code in a programming language - Translating algorithms into code is very much a
mechanical process, involving only a few
decisions. - For each pseudocode block we will see one
foolproof way of translating it to code.
Algorithms are then translated block by block.
17Using Algorithms
- When developing an algorithm, it is a good idea
to make as much use as possible of existing
algorithms (ones you have written or that are
available in a library) - You can put a CALL statement to any existing
algorithm wherever it is needed in the algorithm
you are developing. Be sure you get the ORDER of
the givens and results correctly. - To call an algorithm you need to know its header
but not how it works you must just trust that
it works correctly.
18Information Passing
- When calling an algorithm the call statement and
the header must be identical except for the names
of the givens and results. These are matched
one-to-one in the order they appear. - CALL (T, AvgOutOf25) Alg1(X,Y,Z)
- HEADER (Sum, Avg) Alg1(A,B,C)
- The arrow show how information is passed.
19Testing, Debugging and Maintenance
- Testing looking for errors (bugs) in an
algorithm or program by executing it on test data
(givens) and checking the correctness of the
results. - Debugging locating and correcting an error in
an algorithm or program - Maintenance changing an algorithm or program
that is in use.
20What is an Object?
- An object is a software bundle of variables and
related methods - Software objects are used to model real-world
objects - Real-world objects share two characteristics
They all have state and behavior. - Software objects also have state and behavior. A
software object maintains its state in one or
more variables. And implements its behavior with
methods. - A variable is an item of data named by an
identifier. - A method is a function (subroutine) associated
with an object
21Examples of Object
- Bicycles
- States current gear, current pedal cadence, two
wheels, number of gears - Behaviors braking, accelerating, slowing down,
changing gears - Dogs
- States name, color, breed, hungry
- Behaviors barking, fetching, wagging tail
22What is a Message?
- Software objects interact and communicate with
each other using messages - A single object alone is generally not very
useful. Instead, an object usually appears as a
component of a larger program or application that
contains many other objects. - Through the interaction of these objects,
programmers achieve higher-order functionality
and more complex behavior.
23What is a Message? (2)
- Messages provide two important benefits.
- An object's behavior is expressed through its
methods, so message passing supports all possible
interactions between objects. - Objects don't need to be in the same process or
even on the same machine to send and receive
messages back and forth to each other.
24Components of Message (1)
- When object A wants object B to perform one of
B's methods, object A sends a message to object B - Sometimes, the receiving object needs more
information so that it knows exactly what to do - when you want to change gears on your bicycle,
you have to indicate which gear you want. This
information is passed along with the message as
parameters
25Components of Message (2)
- Three components that comprise a message
- The object to which the message is addressed
(YourBicycle) - The name of the method to perform (changeGears)
- Any parameters needed by the method (lowerGear)
26What is a Class? (1)
- A class is a blueprint, or prototype, that
defines the variables and the methods common to
all objects of a certain kind. - In the real world, you often have many objects of
the same kind. For example, your bicycle is just
one of many bicycles in the world. - Bicycles have some state and behavior in common.
However, each bicycle's state is independent of
and can be different from that of other bicycles.
- Using o-o terminology, we say that your bicycle
object is an instance of the class of objects
known as bicycles.
27What is a Class? (2)
- In object-oriented software, it's also possible
to have many objects of the same kind that share
characteristics rectangles, employee records,
video clips, and so on. Objects of the same kind
are similar and you can create a blueprint for
those objects.
28Class and Instance (1)
- After create the bicycle class, you can create
any number of bicycle objects from the class. - When create an instance of a class, the system
allocates enough memory for the object and all
its instance variables. - Each instance gets its own copy of all the
instance variables defined in the class.
29Class and Instance (2)
- Variables
- Class variable contains information that is
shared by all instances of the class - Instance variable contains information for one
specific instance - Methods
- Class methods invoked directly from the class.
- Instance methods invoked on a particular instance
30Example for Class Variables
- Suppose that all bicycles had the same number of
gears. - Defining an instance variable to hold the number
of gears is inefficient each instance would have
its own copy of the variable, but the value would
be the same for every instance. - Define a class variable that contains the number
of gears. All instances share this variable. If
one object changes the variable, it changes for
all other objects of that type.
31Objects vs. Classes
- The difference between classes and objects is
confusing. - In software, the term "object" is sometimes used
to refer to both classes and instances. - Class is not shaded. It represents a blueprint of
an object rather than an object itself. A
blueprint of a bicycle is not a bicycle. - An object is shaded, indicating that the object
exists and that you can use it.
32What is Inheritance?
- A class inherits state and behavior from its
superclass. - Inheritance provides a powerful and natural
mechanism for organizing and structuring software
programs. - You know a lot about an object by knowing its
class. Even if you don't know what a
penny-farthing is, if I told you it was a
bicycle, you would know that it had two wheels,
handle bars, and pedals. - Object-oriented systems allow classes to be
defined in terms of other classes.
33Example for Inheritance
- Mountain bikes, racing bikes, and tandems are all
kinds of bicycles. In object-oriented
terminology, they are all subclasses of the
bicycle class. Similarly, the bicycle class is
the superclass
34How does Inheritance work? (1)
- Each subclass inherits state (in the form of
variable declarations) and methods from the
superclass. - e.g. Mountain bikes, racing bikes, and tandems
share some states cadence, speed, and some
behaviors braking and changing pedaling speed - Subclasses are not limited to the state and
behaviors provided to them by their superclass.
Subclasses can add variables and methods to the
ones they inherit from the superclass. - e.g. Some mountain bikes have an extra set of
gears with a lower gear ratio.
35How does Inheritance work? (2)
- Subclasses can also override inherited methods
and provide specialized implementations for those
methods. - e.g You had a mountain bike with an extra set of
gears, you would override the "change gears"
method so that the rider could use those new
gears. - Not just one layer of inheritance the
inheritance tree, or class hierarchy, can be as
deep as needed. -- The farther down in the
hierarchy a class appears, the more specialized
its behavior.
36How does Inheritance work? (3)
- In JAVA, the Object class is at the top of class
hierarchy, and each class is its descendant
(directly or indirectly). Object provides
behaviors that are required of all objects
running in the Java Virtual Machine. - e.g. All classes inherit Object's toString
method, which returns a string representation of
the object. -
37Benefits of Inheritance
- Reuse the code in the superclass Subclasses
provide specialized behaviors from the basis of
common elements provided by the superclass. - Programmers can implement superclasses called
abstract classes that define "generic"
behaviors. The abstract superclass defines and
may partially implement the behavior, but much of
the class is undefined and unimplemented. Other
programmers fill in the details with specialized
subclasses.
38Why Abstract Class
- Abstract class The methods can not be specified
at that moment. - e.g. TextMessage, VoiceMessage, FaxMessage all
have a method called play(), how can you
implement play() in the superclass Message?
Message
TextMessage
VoiceMessage
FaxMessage
39What is an Interface? (1)
- An interface is a contract in the form of a
collection of method and constant declarations. - An interface is probably most analogous to a
protocol (an agreed on behavior). - When a class implements an interface, it promises
to implement all of the methods declared in that
interface
40What is an Interface? (2)
- Interface defines a protocol of behavior that can
be implemented by any class anywhere in the class
hierarchy. - Capturing similarities among unrelated classes
without artificially forcing a class
relationship. - Declaring methods that one or more classes are
expected to implement. - Revealing an object's programming interface
without revealing its class.
41Example of Interface
- An inventory program for bicycle doesn't care
what class of items it manages as long as each
item provides certain information, such as price
and tracking number. - The inventory program sets up a protocol of
communication. This protocol comes in the form of
a set of constant and method definitions
contained within an interface. - The inventory interface would define, but not
implement, methods that set and get the retail
price, assign a tracking number, and so on.
42Summary
- Class is a prototype for objects
- Objects are created from classes
- An object's class is its type
- How to create an object from a class
- What constructors are
- What class variables and methods are
- What instance variables and methods are
- How to find out what a class's superclass is
- Interface is a protocol of behavior
43Exercises
- Define classes based on the following scenario
(make reasonable assumption) - Your use an bank card to do some transaction from
a bank machine. - There are three type of transaction withdraw,
deposit and pay bill. - You need input a 4 digits PIN before you can do
any transaction - Bank machine will give you a record after each
transaction
44First Cup of JAVA
45Concise History of Java
- 1991 Group of Sun engineers design a small
portable computer language for consumer devices - 1992 First product delivered by the group
- 1995 Hotjava a WWW browser written in Java
with a built-in interpreter of intermediate
bytecodes starts Java hype - 1996 First official version of Java is released
- 1999 Professional-looking applications start to
appear using the new Swing GUI API
46About Java
- Java technology is both a programming language
and a platform - The Java programming language is a high-level
language - Simple
- Architecture neutral
- Object oriented
- Portable
- Distributed
- High performance
- Interpreted
- Multithreaded
- Robust
- Dynamic
- Secure
47Overview of Java (1)
- Object-Orientation (OO)
- Programs describe interactions between a
collection of objects which are designed to model
some aspect of the real world. For example, an
airline reservation system would involve
Airplanes, Seats, Passengers, Tickets and so on. - Syntax is borrowed from C, while object model
from Smalltalk.
48Overview of Java (2)
- Portability
- As in some version of Pascal, source code is
first compiled into platform-independent
intermediate code bytecode. Unlike Pascal, this
intermediate compilation stage is explicit - Once in the form of bytecodes, programs can be
executed by platform-dependent virtual machines. - Java is often advertised as an interpreter. In
reality, Java source code is always compiled into
bytecodes first. Bytecodes themselves are
interpreted by Java virtual machine (Java VM)
49How Java works?
- The Java programming language is unusual both
compiled and interpreted. - With the compiler, first you translate a program
into an intermediate language called Java
bytecodes The platform-independent codes
interpreted by the interpreter on the Java
platform. The interpreter parses and runs each
Java bytecode instruction on the computer. - Compilation happens just once interpretation
occurs each time the program is executed.
50(No Transcript)
51Why Java Platform-independent
- Java bytecodes help make "write once, run
anywhere" possible. - You can compile your program into bytecodes on
any platform that has a Java compiler. The
bytecodes can then be run on any implementation
of the Java VM. - As long as a computer has a Java VM, the same
program written in the Java programming language
can run on Windows 2000, a Solaris workstation,
or on an iMac.
52(No Transcript)
53Java Programming Environment
- Official address for download http//java.sun.com
/j2se/ - SDK JavaTM 2 Platform, Standard Edition v 1.2 or
v1.3 - Document JavaTM 2 Platform, Standard Edition, v
1.2 or v1.3 Documentation - Java 2 Runtime Environment browser plug-in (not
necessary)
54Java Directory Tree
- \jdk
- docs library documentation in HTML format is
here - bin the compiler and tools
- demo look here for demo
- include files for native methods
- lib library files
- src various subdirectories for the library
source
55Before using Java
- Update the PATH variable
- e.g. In Autoexec.bat
- SET PATHd\Jdk1.2.2\bin
- Set the CLASSPATH if necessary
- e.g. in Autoexec.bat
- SET CLASSPATH. e\myJava
56A Simple Java Program
Everything in Java lives in a class
Access modifier
Name of class
- Public class FirstSample
-
- public static void main(String args)
-
- //Do nothing
- System.out.println("Hello World!")
-
Entrance from command line
Command-line argument
Comments
Semicolon at the end of every statement
A block of code
Call the method println of System.out object
57Several Rules for Start (1)
- Naming rules for classes, methods, variables,
etc. - Begin with a letter A-Z, a-z, - or any
Unicode character that denotes a letter in a
language - Symbols like or _at_ can not be used, nor can
spaces - All characters are case sensitive
- Following with any combination of letters and
digits - Unlimited in length
- Can not use Java reserved words
58Several Rules for Start (2)
- File name must be exactly the same with class
name - Must have a main method for execution
- Braces (opening brace and close brace) are used
to delineate the parts. - Syntax for call method
- object.method(parameters)
59Your First Cup of Java (for Win32)
- /The HelloWorldApp class implements an
application that displays "Hello World!" to the
standard output. - /
- public class HelloWorldApp
-
- public static void main(String args)
-
- // Display "Hello World!" System.out.println("H
ello World!") - System.out.print("Hello World!")
- System.out.println( I am learning Java!")
-
-
60Step by Step (1)
- Create a source file programmer understand
- You can use any text editor to create and edit
source files. - Be Careful When You Type
- Type all code, commands, and file names exactly
as shown. The Java compiler and interpreter are
case-sensitive, so you must capitalize
consistently. - Save as HelloWorldApp.java
61Step by Step (2)
- Compile the source file into a bytecode file -
Java Virtual Machine (Java VM) understand. - Open MS-DOS Prompt
- Go to the directory that you save your source
file - Enter
- Javac HelloWorldApp.java
- Get a class file HelloWorldApp.class
62Step by Step (3)
- Run the program contained in the bytecode file -
computer understand. - Enter
- Java HelloWorldApp
- Have you got the greeting words?
63Algorithm to Program
- Program a Java class with a main method that
is the translation of the algorithm. - Givens, Results and intermediates all get
translated to LOCAL VARIABLES - They all must be declared and given a type.
- Program template
64Exercises
- Define turnEngineOff() and decelerate() methods
for Car class - Translate the Example 2 of algorithm into Java
code
65Fundamental Programming Structures in Java - Data
66Data Type
- Eight primitive types
- Six number types (4 integer and two
floating-point type) - int
- short
- long
- byte
- bloat
- double
- One character type char
- One Boolean type boolean
67Integers (1)
- Numbers without fractional parts
- Negative values are allowed
- Long integer numbers have a suffix L. Hexadecimal
numbers have a prefix 0x
Type Storage requirement Range (inclusive)
int 4 bytes -2,147,483,648 to 2,147,483,647 (just over 2 billion)
short 2 bytes -32,768 to 32,767
long 8 bytes -9,223,372,036,854,775,808L to 9,223,372,036,854,775,807L
byte 1 bytes -128 to 127
68Integers (2)
- Under Java, the ranges of the integer types do
not depend on the machine on which you will run
your Java code. - Platform-independent integer type brings a small
performance penalty (not the worst one).
69Floating-Point Types
- Denote numbers with fractional parts.
- double means the numbers have twice the precision
of the float type - Without a suffix F, a number is always considered
to be of type double.
Type Storage requirement Range
float 4 bytes approximately 3.40282347E38F (6 7 significant decimal digits)
double 8 bytes approximately 1.79769313486231570E 308F (15 significant decimal digits)
70The Character Type
- Denotes characters in the Unicode encoding
scheme. - Designed to handle all characters in all written
languages -- 35,000 are in use - \u prefix with four hexadecimal digits indicates
a Unicode value - www.unicode.org
- Single quotes are used to denote char constants.
- H is a character
- H is a string
71Special characters
Escape Sequence Name Unicode Value
\b backspace \u0008
\t tab \u0009
\n linefeed \u000a
\r carriage return \u000d
\ double quote \u0022
\ single quote \u0027
\\ backslash \u005c
72Boolean Type
- Used for logic testing
- Only two values
- TRUE or FALSE
- Not numbers
73Variables (1)
- Java requests declaring the type of a variable
- Declare a variable by placing the type first,
followed by the name of the variable - e.g.
- byte b //for space-sensitive //consideration
s - int anIntegerVariable
- long aLongVariable
- char ch
74Variables (2)
- Multiple declaration
- int i, j //both are integers
- recommend to declare one variable per line
- You can put declaration anywhere in your code,
but you can only declare a variable once in any
block in a method.
75Expressions
- An expression is a series of variables,
operators, and method calls (constructed
according to the syntax of the language) that
evaluates to a single value - The job of an expression
- To perform the computation indicated by the
elements of the expression - To return a value that is the result of the
computation - e.g.
- System.out.println("The largest byte value is "
largestByte)
76Assignments and Initializations
- After you declare a variable, you should
initialize it by means of an assignment statement - Never have un-initialized variables
- Assignment
- Previously declared variable on the left
- an equal sign ()
- some Java expression with an appropriate value on
the right
77Example of Assignments and Initializations
- Correct assignments
- int foo //this is a declaration
- foo 37 //this is an assignment
- char yesChar
- yesChar Y
- int i 10 //this is an initialization
78Conversions Between Numeric Types (1)
- A binary operations on numeric values of
different types will be treated in the following
fashion - If any of the operands is of type double, the
other one will be converted to a double - Otherwise, if any of the operands is of type
float, the other one will be converted to a
float - Otherwise, if any of the operands is of type
long, the other one will be converted to a long.
79Conversions Between Numeric Types (2)
- Numeric conversion loss of information
- casts give the target type in parentheses,
followed by the variable name. - e.g. double x 9.997
- int nx (int) x
- Value of nx is 9.
- Round use the Math.round method.
- e.g. double x 9.997
- int nx (int)Math.round(x)
- Value of nx is 10.
Return type is long
80Conversions Between Numeric Types (3)
- Certain assignment conversion by assigning the
value of a variable of one type to another
without an explicit cast - byte short int long
- double float
81Constants
- Use keyword final to denote a constant
- final indicates that you can only assign to the
variable once - e.g.
- public class UsesConstants
-
- public static void main(String args)
-
- final double CM_PER_INCH 2.54
- double paperWidth 8.5
- double paperHeight 11
- System.out.println(Paper size in centimeter
paperWidth CM_PER_INCH by - paperHeight CM_PER_INCH )
-
82Class Constants
- Use static final for class constants
- Appear outside method
- e.g.
- public class UserConstants2
-
- public static final double G 9.81
- // gravitation in meters/second squared
- public static void main(String args)
-
- System.out.println(G
- meters per second squared)
-
83Arithmetic Operators (1)
- Arithmetic operators - / are used in Java for
addition, subtraction, multiplication and
division - The / operator denotes integer division if both
arguments are integers, and floating-point
division otherwise. - denoted integer remainder.
- e.g.
- 15 / 6 is 2
- 15 6 is 3
- 11.0 / 4 is 2.75
84Arithmetic Operators (2)
- You can use arithmetic operators in your variable
initialization - e.g.
- int n 5
- int a 2 n // a is 10
- Shortcut for using binary arithmetic operators
- e.g.
- x 4 equal to x x 4
- y 3 equal to y y 3
85Exponentiation
- Java has no operator for raising a quantity to a
power - Use Math.pow method.
- e.g.
- double y Math.pow(x, n)
- y is set to x raised to the power n, which is xn
- The return type of Math.pow is double.
86Increment and Decrement Operators (1)
- Increment operator
- adds 1 to the current value of the variable
- e.g.
- int n 12
- n
- Value of n is 13
- Decrement operator --
- subtracts 1 to the current value of the variable
- e.g.
- int m 7
- m--
- Value of m is 6.
87Increment and Decrement Operators (2)
- Not be applied to number.
- e.g 4 is error
- Two forms make difference in expressions
recommend against using and -- inside other
expressions - postfix evaluate to the old value of the
variable - prefix does addition or subtraction first
- e.g
- int m 7
- int n 7
- int a 2 m // a is 16, m is 8
- int b 2 n //b is 14, n is 8
88Rational and Boolean Operators
- Results of rational and Boolean operators are of
type boolean - Test for equality
- Test for inequality !
- Less than lt
- Greater than gt
- Less than or equal lt
- Greater than or equal gt
- Logic and
- Logic or
- e.g. (3 ! 7) is true
89Bitwise Operators (1)
- Work with any of the integer types
- Work directly with the bits that make up the
integers use masking techniques to get a
individual bits in a number - and
- or
- xor
- not
- e.g. if foo is an integer,
- int fouthBitFromRight (foo 8) / 8
- gives the fourth bit from the right in the
binary representation of foo is one, and a zero
if not
90Bitwise Operators (2)
- gtgt and ltlt operators shift a bit pattern to the
right or left - gtgt operator fills the top bits with the sign bit
- gtgtgt operator fills the top bits with zero
- There is no ltltlt operator
91Parentheses and Operator Hierarchy
- Use parentheses to indicate the order in which
you want operations to be carried out - If no parentheses are used, operations are
performed in the hierarchical order indicated - Operators on the same level are processed from
left to right, except for those that are right
associative
92Operator Precedence
Operators Associativity
. ()(method call) left to right
! -- (unary) (unary) ()(cast) new right to left
/ left to right
- left to right
ltlt gtgt gtgtgt left to right
lt lt gt gt instanceof left to right
! left to right
left to right
left to right
left to right
left to right
left to right
? left to right
- / ltlt gtgt gtgtgt right to left
93Strings
- Denotes a sequences of Unicode characters
- Java has not a built-in string type
- Use methods in String class, each quoted string
is an instance of the String class - e.g.
- String e //and empty string
- String greeting Hello
94Concatenation of Strings
- Java allows to use the sign to
join(concatenate) two strings together - e.g.
- String expletive Expletive
- String PG13 deleted
- String message expletive PG13
- The sign join two strings together in the order
received, exactly as they are given - When you concatenate a string with a value that
is not a string, the value is converted to a
string - e.g.
- String fating PG 13 is PG13
95Substrings
- Exact a substring from a larger string with the
substring method of the String class. - e.g
- String greeting Hello
- String s greeting.substring(0, 4)
- s is Hell
- The first character in a string has position 0.
- The length of string s.substring(a, b) is always
b - a
96String Editing
- To find out the length of a string, use length()
- e.g.
- String greeting Hello
- int n greeting.length() //is 5
- To get at individual characters of a string
s.charAt(n), n is between 0 and s.length() - 1 - e.g.
- String greeting Hello
- char ch greeting.charAt(1) // is e
- No direct way to change a character in strings
use substring() and concatenation to do that
97Testing Strings for Equality (1)
- To test if or not two strings are equal
s.equals(t). -- Return true if the strings and t
are equal, false otherwise - e.g.
- Hello.equals(command)
- To test if two strings are identical except for
the upper/lower case letter distinction
s.equalsIgnoreCase(t) - e.g.
- Hello.equalsIgnoreCase(hello) is true
98Testing Strings for Equality (2)
- Do not use to test if strings are equal, it
only determines whether or not the strings are
stored in the same location - e.g.
- String greeting Hello
- if (greeting Hello) . . . //probably
true - if (greeting.substring(0,4) Hell) .
//probably false - Never use to compare strings
- Go to the Java document to find API of String
99Input from a Command Line Parameter
- public class Test
-
- public static void main(String args)
-
- double x args0
- double y args1
- System.out.println(I got x
- and y
- from command line)
-
-
- C\gtjava Test 3.02
100Formatting Output (1)
- System.out.print(x) print x with the maximum
number of non-zero digits for that type - e.g.
- x 10000.0 / 3.0
- System.out.print(x)
- prints 3333.3333333333335
- To arrange your output neatly NumberFormat class
in java.txt package offers formatters for
numbers, currency values and percentage values - e.g. for United States locale should print
- 3,333.333
- 3,333.33
- 333,333
101Formatting Output (2)
- To obtain a formatter for the default locale
- NumberFormat.getNumberInstance()
- NumberFormat.getCurrencyInstance()
- NumberFormat.getPercentInstance()
- Customize output
- Set minimum or maximum number of integer digits
- setMinimumIntegerDigits()
- setMaximumIntegerDigits()
- Set minimum or maximum number of fractional
digits - setMinimumFractionDigits() default 0
- setMaximumFractionDigits()
102Example of formatting Output
- 1.double x 1000.0 / 3.0
- NumberFormat nf NumberFormat.getNumberInstance
() - String fx nf.format(x)
- //the string is 3,333.33
-
- 2. double x 1000.0 / 3.0
- NumberFormat nf NumberFormat.getNumberInstance
() - nf.setMaximumFractionDigits(4)
- nf.setMinimumIntegerDigits(6)
- String fx nf.format(x)
- //the string is 003,333.3333
103Formatter for different locales
- Object Locale.GERMAN is the local for German
number formatting rules - e.g.
- double x 10000.0 / 3.0
- NumberFormat nf NumberFormat.getNumberInstance
( Locale.GERMAN) - Sysetm.out.println(nf.format(x))
- NumberForamt cf NumberFormat.getCurrencyInstan
ce( Locale.GERMAN) - Sysetm.out.println(cf.format(x))
- Prints
- 3.333,333
- 3.333,33 DM
104Create your own format
- e.g To define a format that shows number with six
digits after the decimal point, but no thousands
separator - DecimalFormat df new decimalFormat(0.)
- System.out.println(df.format(x))
105Formatting characters for DecimalFormat class
Symbol Meaning
0 A digit
A digit dont show if it is a leading or trailing zero
. Location of decimal separator
, Location of grouping separator
Separates formats for positive and negative numbers
- Negative prefix
Divide by 100 and show as percentage
Any other symbols Include symbol in output string
106Excises
- Write a program that tests whether a floating
point number is zero. (Hint You shouldn't
generally use the equality operator with
floating point numbers, since floating point
numbers by nature are hard to match exactly.
Instead, test whether the number is close to
zero.) - Change the code for Algorithm 1 and 2 to get
parameter from command line. - Write a program that calculates the number of US
dollars equivalent to a given number of French
francs. Assume an exchange rate of 6.85062 francs
per dollar. If you want to control the format of
the numbers your program displays, you can use
the DecimalFormat class, which is discussed in
Customizing Formats
107- 4. Write a program that uses the bits in a single
integer to represent the true/false data shown in
the following figure - Include in the program a variable named status,
and have the program print the meaning of status.
For example, if status is 1 (only bit 0 is set)
the program should print something like this
Ready to receive requests - Show your code.
- What is the output when status is 8?
- What is the output when status is 7?
108Fundamental Programming Structures in Java -
Control
109Statements (1)
- Statements are roughly equivalent to sentences in
natural languages. It forms a complete unit of
execution. - The following types of expressions can be made
into a statement by terminating the expression
with a semicolon () - Assignment expressions
- Any use of or --
- Method calls
- Object creation expressions
- e.g
- aValue 8933.234
- aValue
- System.out.println(aValue)
- Integer integerObject new Integer(4)
110Statements (2)
- Two other kinds of statements.
- declaration statement declares a variable.
- e.g.
- double aValue 8933.234
- control flow statement regulates the order in
which statements get executed.
111Know more about blocks (1)
- Block is any number of simple Java statements
that are surrounded by a pair of braces - Blocks define the scope of variables
- Blocks can be nested inside another
- e.g.
- public static void main(String args)
-
- int n
-
- int k // k local to block and //defines
only until the //end of the block -
-
112Know more about blocks (2)
- It is not possible to declare identically named
variables in two nested blocks - e.g.
- public static void main(String args)
-
- int n
-
- int k
- int n // error cant redefine n // in
inner block -
-
113Conditional Statements (1) if Statement
- Syntax
- if (condition) statement
- if (condition) block
- e.g. if (yourSales gt target)
-
- performance Satisfactory
- bonus 100
-
NO
youSales gt target
YES
performance Satisfactory
bonus 100
114Conditional Statements (2) if-else Statement
- Syntax
- if (condition) statement1 else statement2
- if (condition) block1 else block2
- e.g.
- if (yourSales gt target)
-
- performance Satisfactory
- bonus 100
-
- else
-
- performance Unsatisfactory
- bonus 0
-
115- Use else groups with the closest if
- e.g.if (yourSales gt 2 target)
-
- performance Excellent
- bonus 1000
-
- else if (yourSales gt 1.5 target)
-
- performance Fine
- bonus 500
-
- else if (yourSales gt target)
-
- performance Satisfactory
- bonus 100
-
- else
-
- System.out.println(You are fired!)
116? Operator
- Java supports the ternary ? operator
- The expression
- condition ? e1 e2 evaluates to e1 if the
condition is true, to e2 otherwise. - e.g.
- (x lt y) ? xy give the smaller of x and y
- int x 1
- int y 3
- int z (x lt y) ? xy // z is 1
117Multiple Selections - switch Statement
- Conditionally perform statements based on an
integer or char expression - Select only against a char or against all the
integer types but long. - Can not use a range of values
- Each break statement terminates the enclosing
switch statement, and the flow of control
continues with the first statement following the
switch block. - Use the default statement at the end of the
switch to handle all values that aren't
explicitly handled by one of the case statements
118- public class SwitchDemo
- public static void main(String args)
- int day 3
- switch (month)
-
- case 1 System.out.println(Monday") break
- case 2System.out.println(Tuesday")
- break
- case 3
- System.out.println(Wednesday") break
- case 4
- System.out.println(Thursday")
break -
- case 7 System.out.println("June") break
-
-
-
119- public class SwitchDemo2
- public static void main(String args)
- int month 2
- int year 2000
- int numDays 0
- switch (month)
- case 1
- case 3
- case 5
- case 7
- case 8
- case 10
- case 12 numDays 31 break
- case 4
- case 6
- case 9
- case 11 numDays 30
- break
- case 2 if ( ((year 4 0) !(year 100
0)) (year 400 0) ) numDays
29
120- int month 8
- . . .
- switch (month)
- case 1 System.out.println("January") break
- case 2 System.out.println("February") break
- case 3 System.out.println("March") break
-
- case 11 System.out.println("November")
break - case 12 System.out.println("December") break
- default
- System.out.println("Hey, that's not a valid
month!") - break
-
121Breaks
- break statement is used to resume program
execution at the statement immediately following
the current statement. - e.g.
- while (years lt 100)
-
- balance ( balance payment )
- ( 1 interest )
- if ( balance gt goal ) break
- years
-
122Labeled Breaks
- If followed by a label, the program resumes
execution at the labeled statement. - e.g.
- next_client
-
- while (years lt 100)
-
- balance ( balance payment )
- ( 1 interest ) if ( balance gt goal )
break next_client - years
-
123Indeterminate Loops (1)- while loop
- Syntax
- while (condition) block
- The while loop only executes the body of the loop
while a condition is true
NO
condition
YES
Statemets
124- public class WhileDemo
-
- public static void main(String args)
-
- String copyFromMe
- "Copy this string until you "
- "encounter the letter 'g'."
- StringBuffer copyToMe
- new StringBuffer()
- int i 0
- char c copyFromMe.charAt(i)
- while (c ! 'g')
-
- copyToMe.append(c)
- c copyFromMe.charAt(i)
- System.out.println(copyToMe)
-
-
125Indeterminate Loops (2)- do-while loop
- Syntax
- do block while (condition)
- Instead of evaluating the expression at the top
of the loop, do-while evaluates the expression at
the bottom. The statements are executed at least
once
Statemets
condition
YES
NO
126- public class DoWhileDemo
-
- public static void main(String args)
-
- String copyFromMe
- "Copy this string until you "
- "encounter the letter 'g'."
- StringBuffer copyToMe
- new StringBuffer()
- int i 0
- char c copyFromMe.charAt(i)
- do
-
- copyToMe.append(c)
- c copyFromMe.charAt(i) while (c !
'g') -
- System.out.println(copyToMe)
-
-
127Determinate Loops for loop
- Syntax
- for (initialization termination increment )
- block
- Equal to
- initialization
- while (termination)
-
- block
- increment
-
-
128- /Adds the numbers from 1 to 10 and displays the
result - /
- public class ForDemo
-
- public static void main(String args)
-
- int sum 0
- for (int current 1 current lt 10 current)
-
- sum current
-
- System.out.println("Sum " sum)
-
-
129continue Statement
- Skip the current iteration of a for, while , or
do-while loop - The unlabeled form skips to the end of the
innermost loop's body and evaluates the boolean
expression that controls the loop, basically
skipping the remainder of this iteration of the
loop. - The labeled form skips the current iteration of
an outer loop marked with the given label.
130- public class ContinueDemo
-
- public static void main(String args)
-
- StringBuffer searchMe
- new StringBuffer( "peter piper picked
- a peck of pickled peppers")
- int max searchMe.length()
- int numPs 0
- for (int i 0 i lt max i)
- //interested only in p's
- if (searchMe.charAt(i) ! 'p') continue
//process p's numPs - searchMe.setCharAt(i, 'P')
-
- System.out.println("Found " numPs
- " p's in the string.") System.out.println(s
earchMe) -
-
131- public class ContinueWithLabelDemo
- public static void main(String args)
- String searchMe
- "Look for a substring in me"
- String substring "sub"
- boolean foundIt false
- int max searchMe.length()
- - substring.length()
- test for (int i 0 i lt max i)
- int n substring.length()
- int j i
- int k 0
- while (n-- ! 0)
- if (searchMe.charAt(j) !
- substring.charAt(k))
- continue test
-
- foundIt true
- break test
132return Statement
- Exit from the current method.
- The flow of control returns to the statement that
follows the original method call. - Two forms
- Returns a value put the value (or an expression
that calculates the value) after the return
keyword. The data type of the value returned by
return must match the type of the method's
declared return value. - e.g. return count
- Doesn't return a value. When a method is declared
void, - e.g. return
133Excises
- 1. What's wrong with the following code snippet
- if (i 1)
-
- /do something /
-
- 2. Consider the following code snippet.
- if (aNumber gt 0)
- if (aNumber 0) System.out.println("first
string") - else System.out.println("second string")
- System.out.println("third string")
134- What output do you think the code will produce if
aNumber is 3? - Write a test program containing the code snippet
make aNumber 3. What is the output of the
program? Is it what you predicted? Explain why
the output is what it is. In other words, what is
the control flow for the code snippet? - Using only spaces and line breaks, reformat the
code snippet to make the control flow easier to
understand. - Use braces and to further clarify the code
and reduce the possibility of errors by future
maintainers of the code.