2. Review - Lesson 3
Class Libraries
The Random and Math Classes
Formatting Output
Condition statements
The if Statement
The switch Statement
22015 @ Sonia Sousa
3. The Random Class
• Uses the java.util package
• It provides methods
– That performs complicated calculations
– These include:
Random generator = new Random();
generator.nextInt();
generator.nextFloat();
32015 @ Sonia Sousa
4. The Math Class
• Uses the java.lang package
• It provides methods
– That performs various mathematical functions
– These include:
• absolute value
• square root
• exponentiation
4
Math.cos(90);
Math.sqrt(delta);
Math.pow (x,2);
2015 @ Sonia Sousa
5. Formatting Output
• Uses the java.text package
• It provides methods
– that allows you to format
• These are:
–NumberFormat
• formats values as currency or percentages
–DecimalFormat
• formats values (decimal numbers) based on a pattern
2015 @ Sonia Sousa 5
6. DecimalFormat method
• Creating a DecimalFormat instance
String pattern ="#.###";
DecimalFormat fmt = new DecimalFormat (pattern);
• Print out the result
String areaFormat = fmt.format(area);
System.out.println ("The circle's area: " +
areaFormat);
or
System.out.println ("The circle's circumference: "
+ fmt.format(circumference);
2015 @ Sonia Sousa 6
7. NumberFormat
• The java.text.Number format class
– Formats currencies according to a specific Locale
(country)
• Creating a NumberFormat instance
Locale locale = new Locale("ee", "EE");
NumberFormat fmt =
NumberFormat.getCurrencyInstance(locale);
• Print out the result
NumberFormat fmt=
NumberFormat.getCurrencyInstance(locale);
String currency = fmt.format(balance);
2015 @ Sonia Sousa 7
8. Number Format Pattern Syntax
2015 @ Sonia Sousa 8
0 A digit - always displayed, even if number has less digits
(then 0 is displayed)
# A digit, leading zeroes are omitted.
. Marks decimal separator
, Marks grouping separator (e.g. thousand separator)
E Marks separation of mantissa and exponent for
exponential formats.
; Separates formats
- Marks the negative number prefix
% Multiplies by 100 and shows number as percentage
? Multiplies by 1000 and shows number as per mille
¤ Currency sign - replaced by the currency sign for the
Locale. Also makes formatting use the monetary decimal
separator instead of normal decimal separator. ¤¤ makes
formatting use international monetary symbols.
X Marks a character to be used in number prefix or suffix
' Marks a quote around special characters in prefix or suffix
of formatted number.
Pattern Number Formatted
String
###.### 123.456 123.456
###.# 123.456 123.5
###,###.## 123456.78
9
123,456.79
000.### 9.95 009.95
##0.### 0.95 0.95
Example
10. Java program CircleStats
• Write code statements that
– That calculates the area and circumference of a circle
given its radius.
• Prompt for and read a integer value from the user
named radius
• Calculate the area and circumference
area = Math.PI * Math.pow(radius, 2)
circumference = 2 * Math.PI * radius;
– Output the results to 3 decimal places.
DecimalFormat fmt = new DecimalFormat (”#.###”)
fmt.format(area)
fmt.format(circumference)
102015 @ Sonia Sousa
11. Java program FourthPower
• Write code statements that
– Prompt for and read a double value from the user
– Then print the result of raising that value to the
fourth power.
• Math.pow (x,4)
– Output the results to 3 decimal places.
DecimalFormat fmt = new DecimalFormat (”#.###”)
fmt.format()
2015 @ Sonia Sousa 11
12. Java program Calculator
• Write code statements that
– Prompt for and read two double values from the
user
• Then performs
– 5 arithmetic operations (+,-,*,/ and %).
– writes the results on the screen.
– Output the results to 3 decimal places.
2015 @ Sonia Sousa 12
13. Review - Lesson 3
Class Libraries
The Random and Math Classes
Formatting Output
Condition statements
The if Statement
The switch Statement
132015 @ Sonia Sousa
14. Condition statements
• A conditional statement
– Or selection statements
• lets us choose which statement will be executed next
– give us the power to make basic decisions
• The Java conditional statements are the:
– If;
– if-else statement; and
– switch statement;
142015 @ Sonia Sousa
15. Logic of an if statement
condition
evaluated
statement
true
false
152015 @ Sonia Sousa
16. The if Statement
• Let's now look at the if statement in more detail
– The if statement has the following syntax:
16
if ( condition )
statement;
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
If the condition is true, the statement is executed.
If not if it is false, the statement is skipped.
2015 @ Sonia Sousa
17. Logic of an if-else statement
• If the condition is true,
– statement1 is
executed;
– if the condition is false,
statement2 is
executed
2015 @ Sonia Sousa 17
condition
evaluated
statement1
true false
statement2
18. Logic of an if-else statement
condition
evaluated
statement1
true false
statement2
18
Condition 2
evaluated
2015 @ Sonia Sousa
19. Block Statements
• Several statements can be grouped together
– into a block statement delimited by braces
19
if (total > MAX)
{
System.out.println
("Error!!");
errorCount++;
}
2015 @ Sonia Sousa
if (total > MAX)
{
System.out.println
("Error!!");
errorCount++;
}
else
{
System.out.println
("Total: " + total);
current = total*2;
}
20. Nested if Statements
• A statement executed as a result of an if
or else clause
202015 @ Sonia Sousa
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;
21. Indentation
• Remember
– Indentation helps to better read your program,
• Indentation is ignored by the compiler
if (depth >= UPPER_LIMIT)
delta = 100;
else
System.out.println("Reseting Delta");
delta = 0;
21
Despite what the indentation implies, delta will be set to 0
no matter what
2015 @ Sonia Sousa
22. Arithmetic or math expressions
22
Addition
Subtraction
Multiplication
Division
Remainder
+
-
*
/
%
Increment and Decrement
Increment operator
count++; or count = count + 1;
Decrement operator
count--; or count = count – 1;
Equal to
Not equal to
Greater than
Greater tan or equal to
Less than
Less than or equal to
==
!=
>
>=
<
<=
Conditional operators Boolean operators
Conditional-AND
Conditional-OR
Ternary
(shorthand for
if-then-else
statement
&&
||
?:
2015 @ Sonia Sousa
23. The switch Statement
• The switch statement evaluates an expression,
– then attempts to match the result to one of several
possible cases
23
switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
switch
and
case
are
reserved
words
If expression
matches value2,
control jumps
to here
2015 @ Sonia Sousa
24. The switch Statement
• An example of a switch statement:
24
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
2015 @ Sonia Sousa
26. Comparing Data
• When comparing data
– Using boolean expressions,
• it's important to understand the nuances of certain
data types
• Let's examine some key situations:
– Comparing floating point values for equality
– Comparing characters
– Comparing strings (alphabetical order)
262015 @ Sonia Sousa
27. Comparing Float Values
• You should rarely use
– the equality operator (==)
• To compare two floating point values
– float or double
• As two floating point values
– are equal only
• if their underlying binary representations match exactly
• In many situations, you might consider
– two floating point numbers to be "close enough"
• even if they aren't exactly equal
272015 @ Sonia Sousa
28. Comparing Characters or Strings
• We cannot use the relational operators to
compare strings
– Two ways to compare strings and characters
are
• Based on a character set,
– it is called a lexicographic ordering
• Or using the equals method
– to determine if two strings contain exactly the same
characters in the same order
2015 @ Sonia Sousa 28
29. Comparing Strings
• Remember that in Java
– A string is an object
• The String class contains
– the compareTo method
• for determining if one string comes before another
– The equals method
• for determining if one string contains the same
characters as another
• It returns a Boolean result
292015 @ Sonia Sousa
30. Comparing Characters
• Java character data is based on
– the Unicode character set
– Unicode establishes a particular numeric
value for
• each character, and an ordering
– For example,
• the character '+' is less than the character 'J'
– because it comes before it in the Unicode character set
302015 @ Sonia Sousa
31. Comparing Characters
• In Unicode, the digit characters (0-9) are
contiguous and in order
• Likewise, the uppercase letters (A-Z) and
lowercase letters (a-z) are contiguous and
in order
31
Characters Unicode Values
0 – 9 48 through 57
A – Z 65 through 90
a – z 97 through 122
2015 @ Sonia Sousa
32. Lexicographic Ordering
• Lexicographic ordering is not strictly alphabetical
– When uppercase and lowercase characters are mixed
• For example,
– the string "Great" comes before
– the string "fantastic"
– because all of the uppercase letters
• come before all of the lowercase letters in Unicode
• Also, short strings come before longer strings
– with the same prefix (lexicographically)
• Therefore "book" comes before "bookcase"
322015 @ Sonia Sousa
34. Java program FloatCompare
• Write a code statements that compares Float Values
– Prompt for and read 2 float value from the user
– Compares them and returns
if ( Math.abs(f1 - f2) < TOLERANCE) {… }
• This means If
– the difference between the two floating point values is less than the tolerance they
are considered to be equal
• The tolerance could be set to any appropriate level,
– such as 0.000001
– Then print the result
• The float numbers are ("Essentially equal")
• The float numbers are (”Not equal")
2015 @ Sonia Sousa 34
35. Java program StringCompare1
• Write a code statement
– That asks the user for 2 Strings names
– Compares them and returns
• ”Same name”
• ”Not the same names”
• Use the equals method
– It returns a Boolean result (true or false)
if (name1.equals(name2)){
System.out.println ("Same name");
2015 @ Sonia Sousa 35
36. Java program StringCompare2
• Write a code statements that
– asks the user for 2 String names
– Then compare them using the compareTo method
• The comparison is based on the Unicode value of
– this String object is compared lexicographically
• The result is a
– negative integer if this String object lexicographically precedes the argument
string.
» if name1 is less than name2
» zero if name1 and name2 are equal contain the same characters
» returns a positive value if name1 is greater than name2
int result = name1.compareTo(name2);
– Output the results
• Name1 "comes first”
• "Same name”
• Name2 "comes first”
2015 @ Sonia Sousa 36
38. Writing Classes
• The programs we’ve written used
– Classes defined in the Java standard class library
• Now we will begin to design programs that
– Rely on classes that we write ourselves
• The class that contains
– the main method is just the starting point of a
program
• True object-oriented programming is based on
defining classes that represent objects with well-
defined characteristics and functionality
382015 @ Sonia Sousa
39. Encapsulation
• But first you need to understand
– The principle of object oriented language concept
depended on a few concepts
• One is Encapsulation
• It means
– Packaging complex functionality into small pieces of
functions
• You can see it as your application functions wrapped in a box
• Why
– Hiding it complexity make it easier to use
• Easier o debug
• Easier to add more code
2015 @ Sonia Sousa 39
40. Encapsulation
• We’ve learn how to create your program by
putting all your code in the main method
– But when your application get larger It becomes
very difficult to manage
– So instead you need to break your code into
individual classes
• Grouping it functionality for your application
– When you do this you can for instance
• Restrict access to one part of the application
2015 @ Sonia Sousa 40
41. Java application
• Consisted of more than one class
– The starting class has the main method
– Then you have all sort of supporting classes
• Those are called customize methods
– either encapsulate data or functionality, or both
• We can take one of two views of an object:
– internal
• the details of the variables and methods of the class that
defines it
– external
• the services that an object provides and how the object
interacts with the rest of the system
2015 @ Sonia Sousa 41
42. Encapsulation
• From the external view, an object is
– an encapsulated entity, providing a set of specific services
• These services define the interface to the object
• For instance
– One object (called the client) may use another object for the services it
provides
– The client of an object may request its services (call its methods), but it
should not have to be aware of how those services are accomplished
– Any changes to the object's state (its variables) should be made by that
object's methods
• We should make it difficult, if not impossible, for a client to access
an object’s variables directly
• That is, an object should be self-governing
2015 @ Sonia Sousa 42
43. Encapsulation
• An encapsulated object can be thought of as a black
box -- its inner workings are hidden from the client
• The client invokes the interface methods and they
manage the instance data
43
Methods
Data
Client
2015 @ Sonia Sousa
44. Visibility Modifiers
• In Java, we accomplish encapsulation
through the appropriate use of visibility
modifiers
– A modifier is a Java reserved word that
specifies particular characteristics of a
method or data
• Java has three visibility modifiers:
– public, protected, and private
– But first we need to understand the anatomy
of the method
442015 @ Sonia Sousa
46. Method Declarations
• Let’s now examine methods in more detail
– A method declaration Specifies
• the code that will be executed
– when the method is invoked (called)
• In object oriented vocabulary
– A method, as you know is a function or
• A piece of code with a given name
– that can be called (invoked) in parts of an application.
• A function in Java is a member of a class.
2015 @ Sonia Sousa 46
47. Method Control Flow
• When you run an java application
– First thing it looks is for
• The main method
public static void main (String[] args)
– But you can define any method you wont
• To define your own method.
– you need to declare a method within you application.
2015 @ Sonia Sousa 47
48. Method Declarations
• When a method is invoked (called),
– The flow control jumps to the called method and
starts executing its code
• When complete,
– The flow returns to the place where the method
was called and continues
• The invocation may or may not return a
value,
– depending on how the method is defined
482015 @ Sonia Sousa
51. Method Header
51
private static void calc (int num1, int num2)
method
name
return
type
parameter list
The parameter list specifies the type and name of
each parameter
The name of a parameter in the method declaration
is called a formal parameter
Visibility Modifiers
2015 @ Sonia Sousa
52. Method Body
52
private static int calc (int num1, int num2)
{
int sum = num1 + num2;
char result = sum;
return result;
}
The return expression
must be consistent with
the return type
sum and result
are local data
They are created each
time the method is
called, and are
destroyed when it
finishes executing
Input
parameters or
arguments
2015 @ Sonia Sousa
53. Method Header
• Visibility Modifiers: Options available
• Members declared with
– Public visibility
• Is available in the entire application. You can call it everywhere. Or
• In Object oriented words
– can be referenced anywhere
– Private visibility
• The opposite of public. Is only available in that class.
– can be referenced only within that class
– Without a visibility modifier
• have default visibility and
• Can be referenced by any class in the same package
– Protected visibility
• Is an inherence.
• Is available to current class and to any subclasses
• But, we will not we will not cover in this course
2015 @ Sonia Sousa 53
54. Visibility Modifiers
• Public variables violate encapsulation
– because they allow the client to modify the values
directly
• Public constants do not violate encapsulation
because,
– although the client can access it,
– its value cannot be changed
• Therefore instance variables should not be
declared with public visibility
– It is acceptable to give a constant public visibility,
which allows it to be used outside of the class
542015 @ Sonia Sousa
55. Visibility Modifiers
• Methods that provide the object's services are
declared
– with public visibility so that they can be invoked by
clients
• Public methods are also called service methods
• A method created simply to assist a service
method is called a support method
• Since a support method is not intended to be
called by a client, it should not be declared with
public visibility
552015 @ Sonia Sousa
57. Visibility Modifiers
• In Java, we accomplish encapsulation
through the appropriate use of visibility
modifiers
2015 @ Sonia Sousa 57
58. Visibility Modifiers
• In Java, we accomplish encapsulation through the
appropriate use of visibility modifiers
• A modifier is a Java reserved word that specifies
particular characteristics of a method or data
• We've used the final modifier to define
constants
• Java has three visibility modifiers: public,
protected, and private
• The protected modifier involves inheritance,
which we will not cover in this course
582015 @ Sonia Sousa
59. Method Header
• Next characteristics of a method is
– if it is static or not.
• When you wont method to be static.
– This means that
• The method is a class method or an instance of that
class.
– It can be called direct from the class definition
• If you don't know if to add static or not just
– try not to add static and see if you call it in the class or not.
2015 @ Sonia Sousa 59
60. Method Header
• The return type.
• A return statement specifies the value that will be
returned
– return expression return result;
!!! The expression must conform to the return type
• The return type of a method
– indicates the type of value that the method sends back to
the calling location
• void: means the method is not returning anything
• int: means the method is returning an integer
• char: means the method is returning a character
2015 @ Sonia Sousa 60
61. Method Header
• In end of the method Header you should
– open and close parenthesis ()
private static void getInput(){ method body }
– To name your method
• use same rules assigned to variables
– In between parenthesis you add the received
parameters or values
612015 @ Sonia Sousa
62. Declaring Methods with arguments
• When you declare your own custom method
– You can receive parameters or values by declaring
them in the method header
– You can also return parameters or values as well
• Let’s design two custom methods to better
understand how it works
– Called executeFormula, scanning and calc
2015 @ Sonia Sousa 62
63. Anatomy of a Method
Creating reusable code with Methods
64. Java program Wages
• Look for your wages.java program
– Customize two private methods
• Named scanCondition and payCondition
– scanCondition execute scanner commands
– payCondition execute if/else commands
– Call the new customized methods in the main
method
642015 @ Sonia Sousa
65. Anatomy of a Method
Declaring Methods with arguments
66. Passing parameters
• In java variable are always passed by copy
– When a method is called, the actual parameters in the
invocation are copied into the formal parameters in the
method header
Int calc (int s1, int s2)
{
int sum = num1 + num2;
return sum;
}
The sum is = calc (s1, s2);
2015 @ Sonia Sousa 66
67. Java program Aritemetic
• Write a code statement that add two values
– Customize it in a method called AddValues
– This method should receive two values
private static int addvalues(int int1, int int2)
– The assigned two values are 10 and 12
int value1=10;
int value2=12;
–Call the method in the main method and
print out the results
int results= addvalues(value1, value2);
2015 @ Sonia Sousa 67
68. Modifying AddValues
• In Java you can use the same method name more
than once
– You just need to change it signature.
• Try it, use the method called addValues
– Copy/paste it and add one more parameter to the
new one
private static int addvalues(int int1, int int2, int int3)
int sum = int1+int2+int3;
– Assigning one more value (value3) and print the
results and print the result
int value3=10;
2015 @ Sonia Sousa 68
69. Java program (name it testMethod)
• That reads one integers from the user. Then
– Create a method called executeFormula
• This method receives an int x
static int executeFormula(int x)
• The value that will be returned is
return result
• It verifies if x is positive
– If so multiply it by 1000
– Else multiply by 500 if it is negative
– Call executeFormula and Write the result
692015 @ Sonia Sousa
70. Anatomy of a Method
Declaring a Method with arguments
71. Java program Calculator2
• Reuse your previous Calculator program
– That Prompt for and read two double values from the user and then
performs 5 arithmetic operations (+,-,*,/ and %). writes the results on
the screen. And output the results to 3 decimal places.
• Step1: Customize a method called scanning
– This method read a number from the user
• returns an int X
• Step 2: Then… Customize a method called calcSum
– So it receives two int parameters and calculates the sum
static int calc (int s1, int s2)
return sum;
• Call it in the main method
• Ask the user two numbers (by calling scanning)
int s1= scanning();
int s2= scanning();
• Write the result (by calling calcSum).
2015 @ Sonia Sousa 71
72. Java program Calculator2
• Customize 3 more methods
– called calcSub
– called calcDiv
– called calcMult
• Do that by asking the user what operation to
do
– 1= add, 2= substract; 3=divide, 4=multiply
• Use a switch statement to see
– which case the user choose; and
– Adjust your method to calculate the right values
722015 @ Sonia Sousa
73. Sum up
• We’ve learn how to build your own method
• Learn how to
– encapsulate functionality inside methods that are part of
classes
• We‘ve seen, that
– local variables can be declared inside a method
• Keep in mind, that
– when the method finishes,
• all local variables are destroyed (including the formal parameters)
– instance variables, are declared at the class level,
– exists as long as the object exists
2015 @ Sonia Sousa 73