Programming Java
Programming Java
Programming Java
A Couple of Classes
Topics
• This week we will look at two predefined
Java classes
– String
• because strings are useful and we need them in
our example programs
– Scanner
• because we need a way of obtaining keyboard
input for our programs
Objects and Primitive Data
• There are two divisions of data in Java
Objects
• An object consists of both data and
methods.
• A class is the data type of an object.
– A class describes what an object of a
particular type is made of, its data and its
methods.
– A class is merely a description
methods
(little programs)
to process data
String class
• String objects
– contain a sequence of characters,
– and various methods that can do things
with those characters
There are several
dozen methods in
a String object
Question
• What do you suppose that the length()
method of the String object does?
Scanner myScanner =
new Scanner( System.in );
// Declares a Scanner object called myScanner
Read Hours
Read PayRate
Multiply Hours by
PayRate. Store result
in GrossPay.
Display GrossPay
END
Basic Flowchart START Terminal
Symbols
Display message
“How many
hours did you
work?”
– indicate a starting or
hour?”
Multiply Hours by
PayRate. Store
START result in GrossPay.
Display
GrossPay
END Terminal
END
4
Basic Flowchart START
Symbols Display
message “How
many hours did
you work?”
– represented by
“How much do you Input/Output
get paid per
hour?” Operation
parallelograms
– indicate an input or Read PayRate
“How many
Read Hours Display
hours did you GrossPay
work?”
END
5
Basic Flowchart START
Symbols Display
message “How
many hours did
you work?”
rectangles
“How much do
you get paid per
hour?”
– indicates a process
such as a mathematical Read PayRate
computation or variable
assignment
Multiply Hours
by PayRate.
Process Store result in
GrossPay.
Multiply Hours
by PayRate. Display
GrossPay
Store result in
GrossPay. END
6
Four Flowchart Structures
• Sequence
• Decision
• Repetition
• Case
7
Sequence Structure
• A series of actions are performed in sequence
• The pay-calculating example was a sequence
flowchart.
8
Decision Structure
• The flowchart segment below shows a decision
structure with only one action to perform. It is
expressed as an if statement in Java code.
NO YES if (x < y)
x < y? a = x * 2;
Calculate a
as x times 2.
9
Decision Structure
• The flowchart segment below shows how a decision
structure is expressed in Java as an if/else
statement.
NO YES if (x < y)
x < y? a = x * 2;
else
Calculate a Calculate a a = x + y;
as x plus y. as x times 2.
10
Repetition Structure
• The flowchart segment below shows a repetition
structure expressed in Java as a while loop.
while (x < y)
YES x++;
x < y? Add 1 to
x
11
Controlling a Repetition
Structure
• The action performed by a repetition structure must
eventually cause the loop to terminate. Otherwise, an
infinite loop is created.
• In this flowchart segment, x is never changed. Once
the loop starts, it will never end.
• QUESTION: How can this
flowchart be modified so
it is no longer an infinite YES
x < y? Display x
loop?
12
Controlling a Repetition
Structure
• ANSWER: By adding an action within the repetition
that changes the value of x.
YES
x < y? Display x Add 1 to x
13
Case Structure
If years_employed = If years_employed =
2, bonus is set to 200 3, bonus is set to 400
If years_employed = If years_employed is
CASE
1, bonus is set to 100 years_employed any other value,
bonus is set to 800
1 2 3 Other
14
Connectors
END
A
15
Modules
START
•The position of the module
symbol indicates the point the Read Input.
module is executed.
•A separate flowchart can be Call
calc_pay
constructed for the module. function.
Display
results.
END
16
Combining Structures
• This flowchart segment
shows two decision
structures combined. NO YES
x > min?
17
Review
Input/Output
Operation Connector
Process Module
19
Exercise 1
• Draw a flowchart based on the following
algorithm:
1 Start
2 Get the temperature in Fahrenheit
3 Compute the temperature in Kelvin using the
formula
T −32
TK = F + 273.15
1.8
Get TF
T −32
TK = F + 273.15
1.8
Show TK
Stop
21
Exercise 2
• Draw the flowchart for the following
algorithm:
1. Start
2. Get one number in the set
3. Count the numbers as it is obtained
4. If there are still numbers to be obtained,
go back to step 2.
5. Sum the numbers in the set
6. Divide the sum by the number of numbers
in the set to get the average
7. Show the sum and the average
8. Stop
Answer
Start
Calculate mean
Get number
Show sum
Count number Calculate sum and mean
23
Exercise 3
• Draw the 1.
2.
Start
Get h
flowchart for 3.
4.
If h < 11000 then
T ← 288.15 – 6.5*h*10-3
the following 5. Else if h < 20000 then
T ← 216.15
algorithm:
6.
7. Else if h < 32000 then
8. T ← 216.15 + *h*10-3
9. Else if h < 47000 then
10. T ← 228.65 + 2.8*h*10-3
11. Else if h < 51000 then
12. T ← 270.65
13. Else if h < 71000 then
14. T ← 270.65 – 2.8*h*10-3
15. Else T ← 214.65 + 2*h*10-3
16. Endif
17. Show h and T
18. Stop
Answer
Start
Get
altitude h
Yes
h < 11000? T ← 288.15 – 6.5*h*10-3
No
Yes
h < 20000? T ← 216.65
No
Yes
h < 32000? T ← 216.65 + h*10-3
No
B
A
Answer
T ← 214.65 - 2*h*10-3
CPR3013 Programming
Fundamentals
Algorithm Design Using
Selection Construct
Defining Table
Input Processing Output
First pass
1, 2 20 2
3 22
4 18
5 40
6 10
7, 8, 9, 10 display display display display
Second pass
1, 2 100 0
3 100
4 100
5 0
6 0
7, 8, 9, 10 display display display message
CPR3013 Programming
Fundamentals
Algorithm Design Using
Selection Construct
The selection control
structure
• The condition in the IF statement is based on a
comparison of two items and it is expressed with
the following relational operations:
– < less than
– > greater than
– = equals to
– <= less than or equal to
– >= greater than on equal to
– <> not equal to
The selection control
structure
• There are a number of variation of the
selection structure as follows:
1. Simple selection (simple IF statement)
2. Simple selection with null false branch
(null ELSE statement)
3. Combined selection (combined IF
statement)
4. Nested selection (nested IF statement)
The selection control
structure
1. Simple selection (simple IF statement)
– Simple selection occurs when a choice is
made between two alternate paths
depending on the result of a condition
being true or false
– Keywords: IF, THEN, ELSE, ENDIF
The selection control
structure
– Example:
IF account_balance < $300 THEN
service_change = $5.00
ELSE
service_charge = $2.00
ENDIF
The selection control
structure
2. Simple selection with null false branch
(null ELSE statement)
– The null ELSE structure is a variation of
the simple IF structure
– It is used when a task is performed only
when a particular condition is true
– No processing will take place if condition
is false
The selection control
structure
– Example
IF student_attendance = part_time THEN
add 1 to part_time_count
ENDIF
– In this case the part_time_count will be
altered only if he student’s attendance
pattern is part-time
The selection control
structure
3. Combined selection (combined IF statement)
– IF statement with AND or OR connector
– Example IF, AND connector
IF student_attendance = part_time
AND student_gender = female THEN
add 1 to female_part_time_count
ENDIF
– This example, student record will undergo two
test. Only those students who are female and
who attend part-time will be selected;
counter go up
– If either condition is to be found to be false,
the counter will not change
The selection control
structure
– Example IF, OR connector
IF student_attendance = part_time
OR student_gender = female THEN
add 1 to female_part_time_count
ENDIF
– Counter will only increase if
• The student is part-time regardless of gender
• The student is female regardless of attendance
pattern
The selection control
structure
– More than two condition can be linked
together with the AND or OR operators.
IF (record_code = ’23’
OR update_code = delete)
AND account_balance = zero THEN
delete customer record
ENDIF
– Remark → parentheses must be used to
avoid ambiguity
The selection control
structure
– The NOT operator can be used for the
logical negation of a condition
IF NOT (record_code = ’23’) THEN
update customer record
ENDIF
– Note that the AND and OR operators can
also be used with the NOT operator, but
great care must be taken and parentheses
used to avoid ambiguity
The selection control
structure
4. Nested selection (nested if statement)
– Can be classified as
• Linear nested IF statements
• Non-linear nested IF statements
– Linear nested IF statement is used when
a field is being tested for various values
and a different action is to be taken for
each value
The selection control
structure
– It is called Linear due to each ELSE
immediately follows the IF condition to which it
corresponds
IF record_code = ‘A’ THEN
increment counter_A
ELSE
IF record_code = ‘B’ THEN
increment counter_B
ELSE
increment error_counter
ENDIF
ENDIF
– Note there are an equal number of IF, ELSE
and ENDIF and indentation makes it easier to
read and understand
Algorithm using selection
• Example that use the selection control
structure. The problem will be defined,
solution algorithm will be developed and
the algorithm will be manually tested
• Example: Design an algorithm that will
prompt a terminal operator for three
characters, accept those characters as
input, sort them into ascending
sequence and output them onto screen
Algorithm using selection
A. Defining the diagram
Input Processing Output
char_1 Prompt for characters char_1
char_2 Accept 3 characters char_2
char_3 Sort three characters char_3
Output three characters
Algorithm using selection
Read_three_characters
B. Solution 1 Prompt the operator for char_1, char_2, char_3
algorithm 2
3
Get char_1, char_2, char_3
IF char_1 > char_2 THEN
• Solution temp = char_1
algorithm char_1 = char_2
char_2 = temp
requires a ENDIF
series of IF 4 IF char_2
IF char_1 > char_3
> char_3 THENTHEN
statements to temp = char_2
char_2 = char_3
sort the three char_3 = temp
characters into ENDIF
ascending 5 IF char_1 > char_2 THEN
temp = char_1
sequence char_1 = char_2
char_2 = temp
ENDIF
6 Output to the screen char_1, char_2, char_3
END
Algorithm using selection
• Logic of the algorithm is concerned with the
sorting of the three characters into
alphabetic sequence
C. Desk checking
• Set of valid characters will be used to check
the algorithm; the characters k, b and g will be
used
Algorithm using selection
• Input data
Data Set
char_1 k
char_2 b
char_3 g
• Expected results
Data Set
char_1 b
char_2 g
char_3 k
Algorithm using selection
• Desk check table
First pass
1,2 k b g
3 b k k
4 g k k
No
else
Three-way Decisions
• An if statement makes only two-way
decisions.
while(scanner.hasNext())
{
System.out.println(scanner.next());
}
}
}
CPR3013 Programming
Fundamentals
Algorithm Design Using
Iteration Construct
Repetition using the
DOWHILE structure
• Most programs require the same logic
to be repeated for several sets of data
• The most efficient way to deal with
this situation is to establish a looping
structure in the algorithm that will
cause the processing logic to be
repeated a number of times
Repetition using the
DOWHILE structure
• Three different ways that a set of
instructions can be repeated:
– At the beginning of the loop (leading
decision loop)
– At the end of the loop (trailing decision
loop)
– A counted number of times (counted loop)
Repetition using the
DOWHILE structure
• Leading decision loop
– DOWHILE construct is a leading decision
loop – that is the condition is tested
before any statements are executed.
– Format is:
DOWHILE condition p is true
statement block
ENDDO
Repetition using the
DOWHILE structure
– The following processing takes place:
1.Logical condition p is tested
2.If condition p is found to be true, the
statements within the statement block are
executed once. The delimiter ENDDO then
triggers a return of control to the retesting
of condition p
3.If condition p is still true, the statements
are executed again, and so the repetition
process continues until the condition is found
to be false
4.If condition p is found to be false, no
further processing takes place within this
loop
Repetition using the
DOWHILE structure
– There are two important consideration to
be aware of before designing a DOWHILE
loop
• Testing of the condition is at the beginning of
the loop
• The only way to terminate the loop is to render
the DOWHILE condition false
Repetition using the
DOWHILE structure
• Using DOWHILE to repeat a set of
instructions a known number of times
– When a set of instruction is repeated a
specific number of times, a counter can be
used in pseudocode, which is initialised
before the DOWHILE statement and
incremented just before the ENDDO
statement
Repetition using the
DOWHILE structure
• Using DOWHILE to repeat a set of
instruction an unknown number of
times
– When a trailer record or sentinel exists
• Special record or value placed at the end of
valid data to signify the end of that data
– When a trailer record or sentinel does
not exist
• End-of-file (EOF) marker is added when the
file is created as the last character in the
file
Repetition using the
REPEAT…UNTIL structure
• Trailing decision loop
– REPEAT…UNTIL structure is similar to the
DOWHILE structure (group of statements
are repeated in accordance with specific
condition)
– REPEAT…UNTIL structure tests condition
at the end of the loop
– This means that the statement within the
loop will be executed once before the
condition is tested
Repetition using the
REPEAT…UNTIL structure
– If the condition is false, the statement
will then be repeated UNTIL the
condition becomes true
– REPEAT…UNTIL is a trailing decision
loop (the statement are executed once
before the condition is tested)
– Two consideration to be aware of when
using REPEAT…UNTIL
• Loops are executed when the condition is
false
• This structure will always be executed at
least once
Counted repetition
• Counted loop
– Counted repetition occurs only once when
the exact number of loop iterations is
known in advance
– Simple keyword DO is use as follows:
DO loop_index = initial_value to final_value
statement block
ENDDO
Counted repetition
• Expected results
Algorithm Design using
Iteration
• Desk check table
Algorithm Design using
Iteration
• Design the algorithm for the following
problem statement:
counting loop
sentinel-controlled loop
result-controlled loop
Structure of a loop
1. A loop much be initialised
correctly.
2. A logical test must be
preformed to see whether to
enter the loop
3. The body of the loop must
change something so that the
loop will eventually terminate.
• A for loop allows all three
pieces of the loop to be placed
on one line, reducing the change
of programming errors.
Structure
for ( initialize ; test ; change )
loopBody
Equivalent to
int count = 0;
while ( count < 10 )
{
System.out.print( count + " ");
count++ ;
}
Question
• What would the loop output?
int sum = 0;
for ( int x = 0; x < 6; x++ )
{
sum = sum + x ;
System.out.print( x+ " " );
}
System.out.println( “\nsum is: " + sum );
Activity
• rewrite the previous program to use a
while loop
int sum = 0;
int x = 0;
while (x < 6)
{
sum = sum + x ;
System.out.print( x+ " " );
x++;
}
System.out.println( “\nsum is: " + sum );
Omitting Parts of the for
Moving the loop count variable to before
the beginning of the loop
int x = 0;
for ( ; x < 6; x++ )
{
System.out.print( x+ " " );
}
Omitting Parts of the for
• Moving the incremented to the main
part of the loop body.
int x = 0
for ( ; x < 6; )
{
System.out.print( x+ " " );
x++;
}
Scope
• The scope of a variable is the span of
statements were it is valid to use.
• The scope of the variable is the block in
which it is defined.
{
int x = 0;
Scope of variable x
System.out.prinln(x);
}
System.out.prinln(x); Cannot find symbol
Variable Scope and the for loops
• x has the scope of the loop only. when the
condition x<6 is no longer met and the loop
exits the variable x can no longer be used. It
can only be referenced from within the loop.
System.out.println(“\nOdd numbers”);
for ( int j = 1; j < 25; j=j+2 )
System.out.print(j + “ “);
System.out.println(“\nOdd numbers”);
for (j = 1; j < 25; j=j+2 )
System.out.print(j + “ “);
Strings 1
Constructing Strings - recap
Strings 2
Finding the length of a string
Strings 3
Retrieving an Individual Character in a
String
String message = "Welcome to Java";
•Use message.charAt(index)
- a method of the String class
•index starts from 0
•Do not use message[index]
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message W e l c o m e t o J a v a
Strings 4
String Concatenation
String s1 = “Hello”;
String s2 = “World”;
String s3 = s1 + s2;
String s4 = s1.concat(s2); // method of class String
Strings 5
Extracting substrings - 1
public String substring(int beginIndex)
Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (empty string)
Strings 6
Extracting substrings - 2
public String substring(int beginIndex, int endIndex)
Strings 7
Extracting substrings - 3
String is an immutable class.
Values of String objects cannot be changed individually.
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message W e l c o m e t o J a v a
Strings 9
String Comparisons (2) – compareTo()
String s1 = "Welcome";
String s2 = "welcome";
s1.compareTo(s2)
• returns 0 if s1 is equal to s2
• returns a value less than 0 if s1 is lexographically < s2
• returns a value greater than 0 if s1 is lexographically > s2
• Actual value (for Strings) depends on the offset of the 1st two
distinct characters
• if s1 is “abc” & s2 “abg”, compareTo would return –4
• CAUTION – errors will occur if you use comparison operators
(such as >, <=, etc). You must use compareTo with strings.
• Also compareToIgnoreCase(String)
Strings 10
String Comparisons (3) – other methods
• str.equalsIgnoreCase() – ignores the case of the letters
when comparing
• str.startsWith(prefix) – check if string starts with ‘prefix’
• str.endsWith(suffix) check whether string ends with ‘suffix’
Strings 11
String Conversions
•The contents of a string cannot be changed once the string is
created. But you can convert a string to a new string using the
following methods:
toLowerCase()
toUpperCase()
trim() – removes whitespace from both ends of a string
replace(‘a’,’e’)
replaceAll(“a”,”e”)
replaceFirst(“a”, “e”)
Strings 12
Finding character/substring position in a String
public int indexOf(int ch)
• Returns index of first occurrence of the specified
character/substring. Otherwise returns ‘-1’
double d = 5.44;
String s = String.valueOf(d);
s.length(); // returns 4
Strings 14
CPR3013 Programming
Fundamentals
Simple Methods
Real Number Formatting
Lotto
Methods
public class Hello {
public static void main ( String [ ] args )
{
print( "Hello World!“ );
}
public static void print ( String output )
{
System.out.println( output );
}
}
Methods
• Methods are essential in the development of
systems.
• VERY Simple programs can be programmed
without methods.
• More complex software require methods as
they allow:
– Repeated operations to be placed in one section
of code, reducing code and complexity
– Problems to be decomposed into more
manageable pieces.
– Object orientation requires methods as part of
it’s structure
Method signatures
public class Hello {
public static void main ( String [ ] args )
{
print( “A Message” );
print( “ThreeTimes“,3 );
}
public static void print ( String output )
{
System.out.println( output );
}
public static void print ( String output, int times )
{
for (int x = 0 ; x < times ; x++)
System.out.println( output );
}
}
Method Signatures
• The name of the method and it’s list of formal
parameter makes the Method Signature.
public static void print ( String output )
Method Signature
double d = 1.22222222222222d;
float f = 1.22222222222222f;
System.out.println("double :"+d);
System.out.println(" float :"+f);
Formatting
• Two method
– Simple calculation
– Use a pre-defined java class
• Method one
– Multiply the double by 10 or 100 or 1000…
– The multiplication is cast to an int.
– The int result is then divided by 10.0,
100.0, or 1000.0 producing a double as the
result
Formatting method one cont.
class DispNum
{
public static void main (String[] args)
{
double d1 = 1.88888888888888d;
double d2 = 1.8888888888888d;
d1 = ((int)(d1*10))/10.0;
d2 = ((int)(d2*100))/100.0;
System.out.println("d1 :"+d1);
System.out.println("d2 :"+d2);
}
}
Formatting method two
import java.text.NumberFormat;
import java.util.Locale;
class DispNum
{
public static void main (String[] args)
{
double d1 = 123.456789;
double d2 = 123;
double d3 = 10000000.8888888;
NumberFormat nf = NumberFormat.getInstance(Locale.UK);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
System.out.println(str.contains("ummer"));
System.out.println(str.contains("wass"));
}
}
Amended code
public static void makeMeAWinner(int number ,int available)
{
String chosen = "";
for (int x=0; x< number ; x++)
{
int newNumber = (int)((Math.random()*available)+1);
while (chosen.contains(newNumber+""))
{
newNumber = (int)((Math.random()*available)+1);
}
chosen = chosen + " " + newNumber;
System.out.println(newNumber);
}
}
Testing
• All appears to work
however there is a
problem which is only
seen with additional
testing.
• Using (19,20) the
program enters an
infinite loop. WHY?
• Observations:
• All numbers between 10 & 20 shown
• Numbers less than 10 are only in first
half of the output
Problem in the while loop
• Suppose number 18 is the first number
generated. It is placed in the chosen
String (results set)
• The next time round in the loop:
if either a 1 or an 8 is generated then it
will be rejected as a duplicate.
chosen.contains(“1”) will be true.
chosen.contains(“8”) will be true.
Solution
• Make sure that every number in the contains
string has a space either side of it.
• Orignial contains string would look this this
“10 11 14 6 8 5”
• We need to change by adding spaces.
“ 10 11 14 6 8 5 ”
• When we check for the presence of a number
we check that there are spaces surrounding
it.
Changes in red
public static void makeMeAWinner(int number ,int available)
{
String chosen = " ";
for (int x=0; x< number ; x++)
{
int newNumber = (int)((Math.random()*available)+1);
while (chosen.contains(" "+newNumber+" "))
{
newNumber = (int)((Math.random()*available)+1);
}
chosen = chosen + newNumber + " ";
System.out.println(newNumber);
}
}
Results
(18,20) (20,20)
Improvements
• Output the numbers in numerical sequence.
• The number have to be generated before we
can place then into a logical sequence.
Therefore this needs to be done as the last
part of the method.
• We have not looked at a sorting algorithm
(week12). However we can solve this with
techniques that have already covered.
• Any ideas????
Ordered Sequence
public static void makeMeAWinner(int number ,int available)
{
String chosen = " ";
for (int x=0; x< number ; x++)
{
int newNumber = (int)((Math.random()*available)+1);
while (chosen.contains(" "+newNumber+" "))
{
newNumber = (int)((Math.random()*available)+1);
}
chosen = chosen + newNumber + " ";
// System.out.println(newNumber);
}
for (int x=1; x<= available ; x++)
{
if (chosen.contains(" "+x+" "))
System.out.println(x);
}
}
Testing
(10,20) (20,20) (10,1000)
CPR3013 Programming
Fundamentals
Introduction to Arrays
Passing Arrays and other
object to and from methods
Question
If you needed to input 100 numbers to
work out the mean and standard
deviation. Would you create 100
variables to store this data.
• myArray[4] = 2 5 2 5
myArray[2] * 3; 3 70 3 70
4 65 4 15
• int x = 2 5 41 5 51
• int[] values; 0 0
Values
Arrays specify the data type
• Primitive type examples
• int[] intArray = new int[10];
• char[] charArray = new char[20];
• double[] doubleArray = new double[10];
0 74
• Main
Step1
method Step1 1 84
int[] intarr; intarr 2 49
Step3 Step2 3 18
intarr = new int[20]; intarr
4 46
Step3
printArray(intarr); 5 4
6 8
Step4 7 82
• PrintArray(int[] arr) 8 12
The reference value in intarr is arr 9 43
copied into arr. They are two Step4
separate variables but are aliases
for the same object in memory
Returning an array from a method
class ReturnArray
{
public static void main(String[] args)
{
int size = 30;
int[] intarr = rndArray(size);
for (int x = 0 ; x < intarr.length ; x++)
System.out.println(intarr[x]);
}
public static int[] rndArray(int arrSize)
{
int[] arr = new int[arrSize];
for (int x = 0 ; x < arr.length ; x++)
arr[x] = (int)(Math.random()*100);
return arr;
}
}
results
Notes on returning arrays
• The return type is an array in this example an
int array, observe the return type of int[]
• The array is created in the method
rndArray(int) and the values are initialised.
This creates an int array reference variable
arr and creates the array in memory.
• The method rndArray passes back the value
of the array reference, with return arr;
• In the main method the reference which is
passed back from rndArray is placed into the
int array reference variable intarr
Passing by Reference not Value
• Primitive data types are passed by value.
The value in one variable is copied into the
memory location of another variable. They are
separate variable changing the value of one
does not affect the other.
• Objects are passed via their reference.
Essentially the memory reference value is
copied from one reference variable to
another. The two variable are separate BUT
they are aliases for the same object in
memory. They both point to the same object!
Example passing by value and reference
class ByValueAndRef
{
public static void main(String[] args)
{
int intOrd = 10;
int[] intArr = {10};
System.out.println("Ordinary Int :" + intOrd);
System.out.println("Array object :" + intArr[0]);
multByTen(intOrd,intArr);
System.out.println("Ordinary Int :" + intOrd);
System.out.println("Array object :" + intArr[0]);
}
public static void multByTen(int x,int[] y)
{
x *=10;
y[0] *=10;
}
}
Results
Does not work with
every object type
• Immutable objects are objects whose data cannot
change after the object is created.
• String is an immutable data type which you have
already used.
String str = “a string cannot “;
str = str + “be changed”;
• The first line creates a string in memory and places
reference to the object in the variable str
• The concatenation does not alter the string object
but rather creates a new object of type and changes
the reference variable str to point to the new object
• Java garbage collection will free the memory which
the original unreferenced string object uses.
Visual explanation
memory
str = str.toUppercase();
x String object 3
A STRING CANNOT
str BE CHANGED
}
public static void changeString(String str)
{
str = str + “ be changed";
System.out.println("called method: " +str);
}
}
Results
Mutable
• You should compile the following program
outside of class and check it works as
expected.
• Add a String, in addition to the StringBuffer
and check the results are as expected.
• Mutable objects can be changed by the
method they are pass to, so they are not
isolated in the same way as primitive and
immutable types.
StringBuffer Code
class StrStrBuff
{
public static void main(String[] args)
{
StringBuffer strb = null;
strb = new StringBuffer("String Buffer Object");
System.out.println(strb);
changeValue(strb);
System.out.println(strb);
}
public static void changeValue(StringBuffer strb)
{
strb.append("changed");
System.out.println(strb);
}
}
String Array (objects)
String[] planets = new String(6);
Planets[0]=“Mercury”;
Planets[1]=“Venus”; String Object
Planets[2]=“Earth”;
0 Mercury
1 Venus
2 Earth
3
Essentially an array of
4 objects is a list of object
references. Which will
planets 5 either point to an object
or is a NULL
Problem: Letter frequency
• The Caesar cipher which we discussed in
previous weeks are knows as mono alphabetic
substitution ciphers.
• This type of cipher suffers from a problem
that not all letter in the English Language
have the same chance of occurring, some
letters are much more common than others.
• By analysis the letter frequency it is possible
the cryptoanalyse all mono alphabetic ciphers.
All this is based on one
hypothesis
• The letter frequency of English is the same no
matter the source (Shakespeare, dickens, Beatrix
Potter, translated from another language)
freq(str,countLetter);
12
10
0
a b c d e f g h i j k l m n o p q r s t u v w x y z
Ulysses-James Joyce 7.9 1.8 2.5 4.1 12 2.3 2.3 6.1 6.9 0.2 1 4.6 2.7 6.8 7.7 1.9 0.1 5.9 6.5 8.5 2.8 0.8 2.2 0.1 2.1 0.1
Homer-The Iliad 7.5 1.4 2.4 4.6 13 2.4 2.2 6.8 6.5 0.2 0.6 4.2 2.3 6.5 7.2 1.8 0.1 6.7 7.5 8.7 2.8 1 2 0.2 1.6 0.1
Charles Dickens The Pickw ick Papers 7.9 1.4 2.7 4.6 12 2.1 2 5.9 7.2 0.2 1.2 4.2 3 6.9 7.2 2.1 0.1 6.2 6.2 8.6 2.7 0.9 2.5 0.2 2 0.1
Charles Dickens A CHRISTMAS CAROL 7.6 1.6 2.7 4.5 12 2.1 2.5 6.5 6.9 0.1 0.9 3.7 2.4 6.6 8.1 1.9 0.1 6 6.4 9.1 2.8 0.8 2.5 0.1 1.9 0.1
Shakespeare JULIUS CAESAR 8 1.9 2.8 3.8 11 1.9 1.4 5.7 6.9 0 0.8 4.2 2.8 6.1 7.9 1.4 0 6.3 7.8 8.8 4.4 1 2.2 0.1 2.4 0.1
Beatrix Potter Stories 7.9 2.1 2.4 4.9 12 1.9 2.3 6.4 6.5 0.2 1.2 4.2 2.7 6.7 7.1 2.4 0.1 5.2 5.8 9.4 3 0.7 2.4 0.1 2 0
Files and File IO
1
Input and Output Streams
2
IO Streams
• The core Java language does not have any IO
methods.
java.io .*;
3
IO Sources
• An array of bytes
• A String object
• A file
– text
– binary
• other sources, e.g. an internet connection
4
The File Class
• The File class is used to
– obtain file properties
– to create files
– delete files
– rename files.
• The File class is intended to deal with most of
the machine dependent complexities of files &
pathnames in a machine-independent
fashion.
5
Note
• Constructing a File instance does not create a
file on the machine.
• You can create a File instance for any filename
regardless of whether it exists or not.
• Class API
– http://download.oracle.com/javase/6/docs/api/ja
va/io/File.html#File(java.lang.String)
6
The File Class Constructors
• There are several different constructors.
• We are interested in the one with a String parameter.
• The filename is a string.
• Note of file names:
– Do not use absolute filenames in your program as they may
not be platform independent.
– You should use a file name relative to the current directory.
– For example, you may create a File object using
new File(“Welcome.java”)
for the file Welcome.java in the current directory.
Week 8 7
Character Streams and Byte Streams
• Character streams are intended exclusively for
character data.
8
Types of Streams
9
Hierarchy for the java.io Package
dotted clouds
are
abstract
classes.
10
Readers and Writers
11
Java File I/O
• In order to perform I/O you need to create
objects using appropriate Java I/O classes.
12
file processing pattern
• Link to a file
– declare a File object
– pass it to a stream object
• Process the data
while (not end of data)
process data
• Close the file
– close()
13
PrintWriter
• The java.io.PrintWriter class can be used to
write data to a text file.
• Two constructors of interest:
PrintWriter(String filename)
PrintWriter(File file)
15
Example
import java.io.*;
public class WriteData
{
private File file;
private PrintWriter output;
18
Reading from a file
• Java provides many classes to help read text
from a file
– see slide for Readers
• We will use the Scanner class
• See:
http://download.oracle.com/javase/6/docs/api/java
/util/Scanner.html
19
Constructors for Scanner
• Many but one we are interested in is:
public Scanner(File source) throws FileNotFoundException
25
try{
WriteData wd = new WriteData(fileName);
wd.makeLink();
wd.writeToFile();
wd.closeLink();
ReadData rd = new ReadData(fileName);
rd.makeLink();
System.out.println(rd.readFromFile());
System.out.println(rd.readFromFile());
rd.closeLink();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
} 26
Dealing with end of file
• Problem is attempting to read beyond the end
of the data in the file
• Can use Scanner has ‘has...’ methods to solve
problem
• e.g.
if ( input.hasNext() )
read data
else
do not read data
27
Typical file reading pattern
while ( input.hasNext() )
{
// read from file
// process data
}
28
Typical file reading pattern
public String readFromFile2()
{ String output="";
while ( input.hasNext() )
{
String firstName = input.next();
String lastName = input.next();
int score = input.nextInt();
output += firstName + " " + lastName + " " + score + "\n";
}
return output;
}
29
try{
In driver
WriteData wd = new WriteData(fileName);
wd.makeLink();
wd.writeToFile();
wd.closeLink();
ReadData rd = new ReadData(fileName);
rd.makeLink();
System.out.println(rd.readFromFile2());
rd.closeLink();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
30
CPR3013 Programming
Fundamentals
Algorithm Design
The Structure Theorem
• There are three basic control
structures
1. Sequence
2. Selection
3. Repetition
The Structure Theorem
1. Sequence
– Straightforward execution of one
processing step after another
– Represents the first four basic computer
operations
1. Receive information
2. Put out information
3. Perform arithmetic
4. Assign values
The Structure Theorem
– A typical sequence statement in an algorithm might
read:
Add 1 to pageCount
Print heading line1
Print heading line2
Set lineCount to zero
Read customer record
DEPARTMENT OF COMPUTING
FINAL EXAMINATION
SEPTEMBER 2018 SEMESTER
DURATION: 2 HOURS
General Instructions:
1. All answers are to be written in black or blue ink on the answer booklet provided.
2. This examination consists of FOUR questions. Answer ALL questions.
3. This examination paper consists of TWO pages of questions.
4. Students caught copying, or having unauthorized printed materials, pieces of written materials,
or any form of action with intention to cheat and/or copy will be penalized.
CPR3013 Programming Fundamentals
Final Examination, September 2018 Semester: Set A
1. Ms. Blanchett owns 5 apartment buildings. Each building contains 10 apartments that she rent
out for RM 500 per month each. The program should output 12 payment coupons for each of
the 10 apartments in each of the 5 buildings. Each coupon should contain the building number
(1 through 5), the apartment number (1 through 10), the month (1 through 12), and the amount
of rent due.
(a) Design an algorithm by using flow chart for solving the problem as stated above. (12 marks)
(b) Write a complete Java program based on the algorithm you design in Question 1(a).
(10 marks)
[22 marks]
2. Bonus will be given to salespersons varies according to the productivity score of the particular
salesperson. The program should prompt the user to input the productivity score of a salesperson
and output the bonus amount until a sentinel amount of -99 is entered. The bonuses will be
distributed as follow:
3. (a) Create a complete Java program that prompts the user to enter the weight of a parcel (in
gram) and then calculates the shipping fee (in RM). Write a function named computeFee()
with one parameter for the weight of parcel which calculates and returns the shipping fee.
The charges for every 500 grams is RM 4.50. Note that the shipping fee is charged on every
500 grams basis, for example, 700 grams will be charged as 1 kilogram which the fee is RM
9.00. The full program should have a main() function that accepts input from the user for
the weight of the parcel and display the shipping fee by invoking the computeFee() function.
You should print the fee in 2 decimal places. (13 marks)
(b) Write a complete Java program which will prompt the user to key in twelve numbers in an
array, then display each number and the largest number entered. (12 marks)
[25 marks]
Page 1 of 2
CPR3013 Programming Fundamentals
Final Examination, September 2018 Semester: Set A
ii. Complete the constructor that accepts three arguments to initialize all the attributes
shown in Table Q4(a).
(4 marks)
iii. Overload the constructor with no argument by using this reference to initialize the
matchID as 1001, venue as Stadium A, and date as 01-01-2001. (3 marks)
iv. Complete the setVenue() method. (3 marks)
v. Complete the getVenue() method. (3 marks)
vi. Complete the toString() method to return a string with the details of the attributes.
(3 marks)
(b) Write a driver class called MatchDriver with a main method to instantiate an object for
Match class. The details are as shown in Table Q4(b).
Table Q4(b)
Your driver class should display the details of the object. (5 marks)
[25 marks]
THE END
Page 2 of 2
Array
CLO2 Write small programme using selection and iteration to solve basic computing problem
CLO3 Write small programme using function and arrays to solve basic computing problems
Material taken from: Farrell, J., 2011, Java Programming, 6th ed,. Boston: Course Technology
Array
Parallel array
• One with same number of elements as another
• Values in corresponding elements related
Arrays class
• Contains many useful static methods for manipulating arrays
Material taken from: Farrell, J., 2011, Java Programming, 6th ed,. Boston: Course Technology
Topic 12: Exception Handling
Exceptions
• Unexpected or error conditions
• Not usual occurrences
• Causes
• Call to file that does not exist
• Try to write to full disk
• User enters invalid data
• Program attempts to divide value by 0
Exception Handling
• Handling of exceptions
• Object-oriented techniques used to manage Exception errors
• Provides a more elegant solution for handling error conditions
Exception Hierarchy
• Checked exceptions
• Subclass of Exception
• Use for anticipated failures
• Where recovery may be possible
• Some exception types are checked exceptions,which means that a method must do something about them.
• The compiler checks each method to be sure that it does.
• Unchecked exceptions
• Subclass of RuntimeException
• Use for unanticipated failures
• Where recovery is unlikely
• Use of these is ‘unchecked’ by the compiler.
• Cause program termination if not caught.
• This is the normal practice.
• InputMismatchException is a typical example.
try block
• Segment of code in which something might go wrong
• Attempts to execute
• Acknowledging exception might occur
• try block includes:
• Keyword try
• Opening and closing curly brace
• Executable statements
• Which might cause exception
catch block
• Segment of code
• Immediately follows try block
• Handles exception thrown by try block
preceding it
• Can “catch”
• Object of type Exception
• Or Exception child class
• catch block includes:
• Keyword catch
• Opening and closing parentheses
• Exception type
• Name for Exception object
• Opening and closing curly braces
• Statements to handle error condition
• Catch multiple Exceptions
• Examined in sequence
• Until match found for Exception type
• Matching catch block executes
• Each remaining catch block bypassed
• “Catch-all” block
• Accepts more generic Exception argument type: catch(Exception e)
• Unreachable code
• Program statements that can never execute under any circumstances
finally block
• Use for actions you must perform at end of try...catch sequence
• Use finally block to perform cleanup tasks
• Executes regardless of whether preceding try block identifies an Exception
• When finally block used
• finally statements execute before method abandoned
• finally block executes no matter what outcome of try block occurs
• try ends normally
• catch executes
• Exception causes method to abandon prematurely
Exercise
Write a complete Java program that prompts the user to key in two integer values (x & y) and display the result of
x divided by y. Your program should prompt the user to read the number again if the input is incorrect. Hint: You
should consider checking ArithmeticException and InputMismatchException.
1. Write small programmes using selection and iteration to solve basic computing problems.
• Boolean
Use a variable with Boolean data type to keep the value of true or false.
Example: boolean T1 = true, T2 = false;
Example:
boolean T1 = true, T2 = false;
int x = 18, y = 6;
What is the output of the following expressions:
i) T1 || T2
ii) T1 && !T2
iii) !T1 || T2 && (x > y)
CPR3013 Programming Fundamentals Topic 03: Selection
• Selection: if and if...else
What is the output for the following statements?
int x = 34;
char grade= 'F';
if(x >= 80)
grade = 'A';
Exercise 1 :
Write a program that will prompt the user to key in a value in the range of 55 to 80 inclusively. Print
a message to tell the user that he/she entered number correctly or not.
CPR3013 Programming Fundamentals Topic 03: Selection
• Conditional Operator (?:)
• Conditional operator (?:) takes three arguments
– Ternary operator
• Syntax for using the conditional operator is:
expression1 ? expression2 : expression3
• Example:
int x = 2, y = 9, bigger;
bigger = x>y ? x : y;
condition ? true case : false case
is same as:
if(x>y)
bigger = x;
else
bigger = y;
• switch Structures
Scanner input = new Scanner(System.in);
int option;
System.out.print("Key in your option: ");
option= input.nextInt();
switch(option){
case 1 : System.out.println("You key in 1");
case 2 : System.out.println("You key in 2");
break;
case 3 : System.out.println("You key in 3");
case 4 : System.out.println("You key in 4");
break;
default: System.out.println("Invalid\n");
}
Exercise 2 :
Write a program to prompt user to key in an integer value. Check if the value is positive or negative.
Exercise 3 :
Write a program to prompt the user key in an integer value, check whether the number is even or
odd.
CPR3013 Programming Fundamentals Topic 04: Iteration
Upon completion of the topic, the student is able to:
1. Write small programmes using selection and iteration to solve basic computing problems.
initial statement
Logical
false
expression
true
statement
update statement
Initialize
update
Logical expression
false
true
statement
CPR3013 Programming Fundamentals Topic 04: Iteration
initial statement
statement
update statement
true
Logical
false
expression
b) int i=3;
while(i<100) {
System.out.println(i);
i *= 3; // i = i*3;
}
Learning to program
Topic 5
Knowledge
Topic 4
Topic 3
Topic 2
Topic 1
Reading
• Get used to reading, even if what you read
does not make much sense at the time??
What for??
• Be prepared for a massive amount of new
terminology
• Don’t be scared – you will sound like a
spaceman soon enough!!
• Get to the library as soon as possible
• Get at least one Java book out.
• The learning curve is hard
• Learning is good .. Love it!
Getting set-up at home
• We are using Java Development Kit JDK1.8
• We Offer ZERO support for home computers and laptops
• CPR3013
– Set-up and create the same set-up we have
– Site links for free software
– The on-line Java tutorial from sun
– Unit slides and labs – collect missed notes online
– Software from http://www.jcreator.com Or Netbeans from
http://netbeans.org
•
Question
Here is the first line of a Java program:
public class AddUpNumbers
What should the source file be named?
What will the compiler name the bytecode
file?
AddUpNumbers.java
AddUpNumbers.class
Java Virtual Machine
Running the Program
• You are using JCreator so you need to
select the appropriate icon to make the
program run
• In a Command Window you would issue
the command:
java Hello
Question
• What role in Java programming does each of
the following files play?
Source code file.
Bytecode file.
Answer
• Source code file.
• A text file in the Java language created by a programmer
with a text editor.
• Bytecode file.
• A file of machine language for the Java virtual machine
created by a Java compiler.
Example Source Program
public class Hello
{
public static void main ( String[ ] args )
{
System.out.println("Hello World!");
}
}
• The file must be named Hello.java
– The case of the letters is important
• Class is a Java reserved word
– A class is a section of program
– Everything that makes up a class is placed
between the first brace ( { ) and the
matching last brace ( } ).
• The name of the class is up to you but
– Should start with an upper case letter
– May consist of letters or digits
– May NOT have spaces
Between the Braces
• All of our small Java programs look
something like this:
NOTE:
public class YourName Braces always
{ come in pairs
….. { }
}
Another NOTE:
We want you to always write the first line as
public class …
The word public is optional in some cases but in others leaving it
out can cause errors
public static void main ( String[] args )
Capital S
. ( ) ;
Syntax Errors
• A syntax error is a "grammatical error" in using
the programming language.
• The compiler tried to translate the source code into
bytecode but failed as there is something it does not
understand or expect. It will stop it processing and
give you a message.
• The compiler generated an error message showing
where the compiler got confused. It will also tell you
why it got confused
• The compiler did not create a new bytecode file
because it stopped translating when it got to the
error
Edit, Compile, Run Cycle
1. Edit the program in JCreator.
2. Save the program to the hard disk
3. Compile the program
4. If there are syntax errors, go back to step
1.
5. Run the program
6. If it does not run correctly, go back to step
1.
7. When it runs correctly, quit.
Comments 1
• A comment is a note written to a human
reader of a program
• Three types of comment:
– // single line comment
– /* multi line comment
can be spread over several
lines
*/
Comments 2
• The third type of comment is special and is
used at the top of your program.
• Later you will find out how it helps when
generating documentation
• /**
* brief description of program
* @author YOUR NAME
* @version DATE OR VERSION NUMBER
*/
/**
* Hello world program to demonstrate comments
*
* @author Lai Kim Min
* @version 02-01-2016
*/
• Examples
int x; // Declare x to be an integer variable;
double radius; // Declare radius to be a
char a; // Declare a to be a character variable;
Data Types
• Computer memory stores arbitrary bit
patterns.
• As with a string of letters, the meaning
of a string of bits depends on how it is
used.
• The particular scheme that is being
used for a particular string of bits is a
data type.
Data Types continued
• A data type
– Is a scheme for using bits to represent
values.
– Values are not just numbers, but any kind
of data that a computer can process.
– All values in a computer are represented
using one data type or another.
Question
0000000001100111
is a pattern of 16 bits that might be
found somewhere in computer memory.
What does it represent?
No.
Data of type short can be only in
the range -32,768 to +32,767.
• When you write a program you do not have to
know how to represent a number in bits.
• You can type the number just as you would on
a typewriter.
• This is called a literal
• For example, 125 literally represents the
value one hundred twenty five.
• Example Integer literals
– 125 -32 16 0 -123987
• A 64 bit long literal has a upper case 'L' or
lower case 'l' at the end.
– 125L -32L 16L 0l -123987l
Question
• Is the following an integer literal?
197.0
No
It has a decimal point
Program 1
The following program uses primitive data type short:
class ShortEg
{
public static void main ( String[] args )
{ value in this program is a
short value = 32; variable
System.out.println("A short: " + a name for a section of memory
that holds data using a
value); particular data type.
} In this case value will be the
} name for 16 bits of main
memory that uses short to
represent an integer.
This program puts 32 into value.
Then it writes out:
A short: 32
Floating Point Literals
• floating point literals have a decimal point in
them, and no commas (no thousand's
separators):
123.0
-123.5
-198234.234
0.00000381
•
• Note: Literals written like the above will
automatically be of type double
Question
• Do you think that using float instead of
double saves a significant amount of
computer memory?
No.
For most programs using variables of type double
will cost only a few extra bytes in a program
thousands of bytes long.
Note
• Either of the following also works:
double rats = 8912 ;
• or
double rats = 8912.0 ;
• but the first is sloppy so do not do it!
Scientific Notation
• You will sometimes see scientific
notation.
• The following are all double-precision
literals:
1.23E+02
-1.235E+02
-1.98234234E+05
3.81E-06
• The big "E" means "times 10 to the
power of" .
Question
• What is the following number if written
out the usual way: 1.9345E+03
1934.5
The char Primitive Data Type
• Characters are very common in computers.
• The primitive data type for characters is
named char.
• The char type represents a character using
16 bits.
• Java uses 16 bits so that a very large number
of characters can be represented, nearly all
of the characters in all of the World's
languages.
• The method used is called Unicode.
• Here is a 16 bit pattern:
000000000110011
• If you know that these 16 bits are of
data type char, then you could look in a
table and discover that they represent
the character 'g'.
• the same 16 bits represent the integer
103 if they are regarded as data type
short.
• Knowing the data type of a pattern is
necessary to make sense of it.
Observations on char
• Upper and lower case characters are
represented by different patterns.
• Punctuation and special characters are also
char data.
• There are also special characters, like the
space character that separates words.
• Control characters are bit patterns that
show the end of a line or where to start
pages.
• Primitive type char represents a SINGLE
character.
Character Literals
• In a program, a character literal is surrounded with
an apostrophe on both sides:
'm' 'y' 'A'
• In a program, control characters are represented
with several characters inside the apostrophes:
'\n‘ '\t'
• Each of these is what you do in a program to get a
single char.
– the first one represents the 16 bit newline character
– the second one represents the tabulation character.
• What is wrong with the following char
literal: "W"
is a declaration of a variable.
• A declaration of a variable is where a program
says that it needs a variable.
• For our small programs, declaration
statements will be placed between the two
braces of the main method.
• The declaration gives a name and a data type
for the variable.
• It may also ask that a particular value be
placed in the variable
public class Example
{
public static void main ( String[] args )
{
// declaration of a variable and initialises
// the value.
int payAmount = 123;
System.out.println("The variable contains: “
+ payAmount );
} The line The + joins
the two
} int payAmount = 123; items in
is a declaration of a variable. the output
The effect of declaring a
variable in Java
Computer Memory Java Instruction
score
int score ;
Syntax of Variable Declaration
• dataType variableName;
– declares a variable, declares its data type, and
reserves memory for it. It says nothing about what
value is put in memory.
• dataType variableName = initialValue ;
– The second way declares a variable, declares its
data type, reserves memory for it, and puts an
initial value into that memory. The initial value
must be of the correct dataType.
• dataType variableNameOne, variableNameTwo ;
– The third way declares two variables, both of the
same data type, reserves memory for each, but
puts nothing in any variable. You can do this with
more than two variables, if you want
Names for Variables
• Use only the characters 'a' through 'z', 'A' through
'Z', '0' through '9', character '_', and character '$'.
• A name can not contain the space character.
• Do not start with a digit.
• A name can be any length.
• Upper and lower case count as different characters.
– So SUM and Sum are different names.
• A name must not already be in use in this part of the
program
• A name can not be a reserved word.
long good-by ;
short shrift = 0;
double bubble = 0, toil= 9, trouble = 8
byte the bullet ;
int double;
char thisMustBeTooLong ;
int 8ball;
Example Program
public class Example
{
public static void main ( String[] args )
{
int hoursWorked = 40;
double payRate = 10.0, taxRate = 0.10;
System.out.println("Hours Worked: " + hoursWorked );
System.out.println("pay Amount : " +
(hoursWorked * payRate) );
System.out.println("tax Amount : " +
(hoursWorked * payRate * taxRate) );
}
} Order is important we need to
declare a variable before we
use it.
Java Naming Convention
1. the name of a class starts with a
Capital case letter
2. the name of a variable starts with a
lower case letter
3. if a name consists of several words the
first word starts with a lower case and
each of the rest an upper case, e.g
myMarkForTheModule
Assignment Statements
• So far, we have been using the value
initially put into a variable, but not
changing the value that a variable holds.
• Of course, variables are expected to
vary by having new values placed into
them as the program runs.
• An assignment statement changes the
value that is held in a variable
public class Example3
{
public static void main ( String[] args )
{
int payAmount ; //a declaration
payAmount = 123; //an assignment statement
System.out.println("The variable contains: "
+ payAmount );
}
}
Assignment Statement Syntax
• variableName = expression ;
– The equal sign "=" means "assignment."
– variableName is the name of a variable that
has been declared somewhere in the
program.
– expression is a collection of characters that
calls for a value.
Assignment Statement Syntax
• An assignment statement asks for the
computer to perform two steps, in
order:
– Evaluate the expression (that is: calculate a
value.)
– Store the value in the variable.
– For example, the assignment statement:
• sum = 32 + 8 ; asks for two actions:
– Evaluate the Expression — 32 + 8 is calculated,
yielding 40.
– Store the value in the variable. — 40 is placed in sum
Example Assignment Statements
• weeklyPay = 200.59 ;
• totalPay = 52 * weeklyPay;
• extraPay = totalPay / 12 + weeklyPay * bonus;
• extraPay = (totalPay / 12 + weeklyPay )*
bonus;
% Remainder
+ Addition
- minus
Quiz: Which ones are correct?
• 25
• 25 - value
• 2( a - b )
• (a-b) * (c-d)
• A - b/c + D
• -sum + partial
• ( (x+y) / z ) / ( a - b )
• ( (m - n) + (w-x-z) / (p % q )
Arithmetic Operators
3.5/2.0 = 1.75
Casting
• Variables and expressions can be covered
from one data type into another data type by
using casting.
• We have implicit casting and explicit casting.
• Implicit casting is when we move from a
smaller data type to a larger one. For example
int x = 100;
long y = x;
DURABLE = 0.441;
How many 100’s 10’s 1’s
• We can use simple mathematics to help
solve everyday problems.
• How do we split the number
• 453 into 4, 5, 3 by using mathematics
System.out.println(digit);
// produces output of 9
System.out.println(number);
// produces output of 87
//CONTINUE CODE…..