[6] Programming Language Fundamentals (Part 3)
[6] Programming Language Fundamentals (Part 3)
LANGUAGE
FUNDAMENTALS
1
2 DEFINING YOUR OWN
CLASSES (PART 2)
RETURNING AN OBJECT
FROM A METHOD
As we can return a primitive data value from a
method, we can return an object from a method
also.
We return an object from a method, we are
actually returning a reference (or an address) of
an object.
− This means we are not returning a copy of an
object, but only the reference of this object
3
SAMPLE OBJECT-RETURNING
METHOD
Here's a sample method that returns an object:
Return
Returntype
typeindicates
indicates
the
the class of anobject
class of an object
we're returning from
we're returning from
the
themethod.
method.
public Fraction simplify( ) {
Fraction simp;
int num = getNumberator();
int denom = getDenominator();
int gcd = gcd(num, denom);
simp = new Fraction(num/gcd, denom/gcd);
return simp;
} Return
Returnan
aninstance
instanceof
of
the Fraction class
the Fraction class
4
A SAMPLE CALL TO simplify
public Fraction simplify( ) {
int num = getNumerator();
f1 = new Fraction(24, 26); int denom = getDenominator();
int gcd = gcd(num, denom);
f1
simp
f2
: Fraction : Fraction
numerator numerator
24 2
denominator denominator
36 3
A SAMPLE CALL TO simplify
(CONT’D) public Fraction simplify( ) {
int num = getNumerator();
f1 = new Fraction(24, 26); int denom = getDenominator();
int gcd = gcd(num, denom);
f1
simp
f2
: Fraction : Fraction
this
7
THE USE OF this IN THE add
METHOD
public Fraction add(Fraction frac) {
int a, b, c, d;
Fraction sum;
return sum;
}
f3 = f1.add(f2)
Because
Because f1 f1 isis
the
the receiving
receiving
object
object (we're
(we're
calling
calling f1's
f1's
method),
method), so so
the
the reserved
reserved
word
word this
this is
is
referring
referring toto f1.
f1.
f3 = f2.add(f1)
This
This time,
time,
we're
we're calling
calling
f2's
f2's method,
method, so so
the
the reserved
reserved
word
word this
this is
is
referring
referring toto f2.
f2.
USING this TO REFER TO
DATA
MEMBERS
In the previous example, we showed the use of
this to call a method of a receiving object.
It can be used to refer to a data member as
well.
class Person {
int age;
11
OVERLOADED METHODS
Methods can share the same name as long as
− they have a different number of parameters (Rule
1) or
− their parameters are of different data types when
the number of parameters is the same (Rule 2)
}
CALL-BY-VALUE PARAMETER
PASSING
When a method is called,
− the value of the argument is passed to the
matching parameter, and
− separate memory space is allocated to store this
value.
This way of passing the value of arguments is
called a pass-by-value or call-by-value
scheme.
Since separate memory space is allocated for
each parameter during the execution of the
method,
− the parameter is local to the method, and therefore
− changes made to the parameter will not affect the
value of the corresponding argument.
CALL-BY-VALUE EXAMPLE
class Tester {
public void myMethod(int one, double two ) {
one = 25;
two = 35.4;
}
}
Tester tester;
int x, y;
tester = new Tester(); 10 20
x = 10; produce
y = 20; s
tester.myMethod(x, y);
System.out.println(x + " " + y);
MEMORY ALLOCATION FOR
PARAMETERS
MEMORY ALLOCATION FOR
PARAMETERS
PARAMETER PASSING: KEY
POINTS
1. Arguments are passed to a method by using the pass-
by- value scheme.
2. Arguments are matched to the parameters from left to
right. The data type of an argument must be
assignment-compatible with the data type of the
matching parameter.
3. The number of arguments in the method call must
match the number of parameters in the method
definition.
4. Parameters and arguments do not have to have the
same name.
5. Local copies, which are distinct from arguments, are
created even if the parameters and arguments share
the same name.
6. Parameters are input to a method, and they are local to
the method. Changes made to the parameters will not
ORGANIZING CLASSES INTO
PACKAGE
For a class A to use class B, their bytecode files
must be located in the same directory.
− This is not practical if we want to reuse
programmer-defined classes in many different
programs.
The correct way to reuse programmer-defined
classes from many different programs is to
place reusable classes in a package.
A package is a Java class library.
CREATING A PACKAGE
The following steps illustrate the process of
creating a package name myutil that includes
the Fraction class.
1. Include the statement
package myutil;
as the first statement of the source file for the
Fraction class.
2. The class declaration must include the visibility
modifier public as
public class Fraction {
...
}
CREATING A PACKAGE
The following steps illustrate the process of
creating a package name myutil that includes
the Fraction class.
3. Create a folder named myutil, the same name
as the package name. In Java, the package must
have a one-to-one correspondence with the
folder.
4. Place the modified Fraction class into the myutil
folder and compile it.
5. Modify the CLASSPATH environment variable to
include the folder that contains the myutil
folder.
USING javadoc COMMENTS
Many of the programmer-defined classes we
design are intended to be used by other
programmers.
− It is, therefore, very important to provide
meaningful documentation to the client
programmers so they can understand how to use
our classes correctly.
/**
* Returns the sum of this Fraction
* and the parameter frac. The sum
* returned is NOT simplified.
*
* @param frac the Fraction to add to this this javadoc
* Fraction will produce
*
* @return the sum of this and frac
*/
public Fraction add(Fraction frac) {
...
}
. . .
EXAMPLE: javadoc OUTPUT
29 CHARACTERS AND
STRINGS
CHARACTERS
In Java, single characters are represented using
the data type char.
Character constants are written as symbols
enclosed in single quotes.
Characters are stored in a computer memory
using some form of encoding.
ASCII, which stands for American Standard
Code for Information Interchange, is one of
the document coding schemes widely used
today.
Java uses Unicode, which includes ASCII, for
representing char constants.
ASCII ENCODING
9
For
Forexample,
example,
character
character'O'
'O'
isis79 (row
79 (row
70 O value
value7070++
col
colvalue
value99==
79).
79).
UNICODE ENCODING
The Unicode Worldwide Character
Standard (Unicode) supports the interchange,
processing, and display of the written texts of
diverse languages.
Java uses the Unicode standard for representing
char constants.
char ch1 = 'X';
System.out.println(ch1);
X
System.out.println( (int) ch1); 88
CHARACTER PROCESSING
char ch1, ch2 = ‘X’; Declaration
Declarationandand
initialization
initialization
This
Thiscomparison
comparison
‘A’ < ‘c’ returns
returnstrue
truebecause
because
ASCII
ASCII value of'A'
value of 'A'isis65
65
while that of 'c' is 99.
while that of 'c' is 99.
STRINGS
A string is a sequence of characters that is
treated as a single value.
Instances of the String class are used to
represent strings in Java.
We can access individual characters of a string
by calling the charAt method of the String
object.
ACCESSING INDIVIDUAL
ELEMENTS
Individual characters in a String accessed with
the charAt method.
String name = "Sumatra";
0 1 2 3 4 5 6
S u m a t r a
name name.charAt( 3 )
The
Themethod
methodreturns
returnsthe
the
This
Thisvariable
variablerefers
refersto
to character
the whole string. character at position##
at position
the whole string. 3.
3.
EXAMPLE: COUNTING
VOWELS
char letter;
System.out.println("Your name:");
String name = scanner.next(); //assume ‘scanner’ is created properly
int numberOfCharacters = name.length();
int vowelCount = 0;
Here’s
Here’sthe
thecode
code
for (int i = 0; i < numberOfCharacters; i++) { to count the
to count the
letter = name.charAt(i); number
numberof ofvowels
vowels
in the input
in the input
if ( letter == 'a' || letter == 'A' || string.
string.
letter == 'e' || letter == 'E' ||
letter == 'i' || letter == 'I' ||
letter == 'o' || letter == 'O' ||
letter == 'u' || letter == 'U'
) {
vowelCount++;
}
}
System.out.print(name + ", your name has " + vowelCount + " vowels");
EXAMPLE: COUNTING ‘Java’
int javaCount = 0;
Continue
Continuereading
readingwords
words
boolean repeat = true; and count how many
and count how many
String word; times
timesthe
theword
wordJava
Java
Scanner scanner = new Scanner(System.in); occurs in the input,
occurs in the input,
ignoring
ignoringthe
thecase.
case.
while ( repeat ) {
System.out.print("Next word:");
word = scanner.next();
if ( word.equals("STOP") ) { Notice
Noticehow
howthe
the
repeat = false; comparison
comparison isdone.
is done.We
We
are not using the ==
are not using the ==
operator.
operator.
} else if ( word.equalsIgnoreCase("Java") ) {
javaCount++;
}
}
OTHER USEFUL STRING
OPERATORS
Method Meaning
compareTo Compares the two strings.
str1.compareTo( str2 )
substring Extracts the a substring from a string.
str1.substring( 1, 4 )
trim Removes the leading and trailing spaces.
str1.trim( )
valueOf Converts a given primitive data value to a string.
String.valueOf( 123.4565 )
first third
character second character
is 5 character is any digit
is 1, 2, or 3 between 1 and 7
REGULAR EXPRESSIONS
The pattern is called a regular expression.
Rules:
− The brackets [ ] represent choices
− The asterisk symbol * means zero or more
occurrences.
− The plus symbol + means one or more
occurrences.
− The hat symbol ^ means negation.
− The hyphen – means ranges.
− The parentheses ( ) and the vertical bar | mean a
range of choices for multiple characters.
REGULAR EXPRESSION
EXAMPLES Description
Expression
[013] A single digit 0, 1, or 3.
[0-9][0-9] Any two-digit number from 00 to 99.
[0-9&&[^4567]] A single digit that is 0, 1, 2, 3, 8, or
9.
[a-z0-9] A single character that is either a
lowercase letter or a digit.
[a-zA-z][a-zA-Z0-9_$]* A valid Java identifier consisting of
alphanumeric characters,
underscores, and dollar signs, with
the first character being an alphabet.
[wb](ad|eed) Matches wad, weed, bad, and beed.
(AZ|CA|CO)[0-9][0-9] Matches AZxx,CAxx, and COxx,
where x is a single digit.
THE replaceAll METHOD
The replaceAll method replaces all
occurrences of a substring that matches a given
regular expression with a given replacement
string.
Replace all vowels with the symbol @
String originalText, modifiedText;
modifiedText =
originalText.replaceAll("[aeiou]","@");
THE Pattern AND Matcher
CLASSES
The matches and replaceAll methods of the
String class are shorthand for using the
Pattern and Matcher classes from the
java.util.regex package.
If str and regex are String objects, then
str.matches(regex);
is equivalent to
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
matcher.matches();
THE compile METHOD
The compile method of the Pattern class
converts the stated regular expression to an
internal format to carry out the pattern-
matching operation.
This conversion is carried out every time the
matches method of the String class is
executed, so it is more efficient to use the
compile method when we search for the same
pattern multiple times.
THE find METHOD
The find method is another powerful method of
the Matcher class.
− It searches for the next sequence in a string that
matches the pattern, and returns true if the
pattern is found.
When a matcher finds a matching sequence of
characters, we can query the location of the
sequence by using the start and end methods.
THE String CLASS IS
IMMUTABLE
In Java a String object is immutable.
− This means once a String object is created, it
cannot be changed, such as replacing a character
with another character or removing a character
− The String methods we have used so far do not
change the original string. They created a new
string from the original. For example, substring
creates a new string from a given string.
The String class is defined in this manner for
efficiency reason.
EFFECT OF IMMUTABILITY
We can do this
because String
objects are
immutable.
THE StringBuffer CLASS
In many string processing applications, we
would like to change the contents of a string. In
other words, we want it to be mutable.
Manipulating the content of a string, such as
replacing a character, appending a string with
another string, deleting a portion of a string,
and so on, may be accomplished by using the
StringBuffer class.
StringBuffer EXAMPLE
StringBuffer word = new StringBuffer("Java");
word.setCharAt(0, 'D');
word.setCharAt(1, 'i');
word word
Before After
SAMPLE PROCESSING
Replace all vowels in the sentence with ‘X’.
char letter;
String inSentence = JOptionPane.showInputDialog(null, "Sentence:");
StringBuffer tempStringBuffer = new StringBuffer(inSentence);
int numberOfCharacters = tempStringBuffer.length();
letter = tempStringBuffer.charAt(index);
An array is like an
object!
ACCESSING INDIVIDUAL
ELEMENTS
Individual elements in an array accessed with
the indexed expression.
rainfall
0 1 2 3 4 5 6 7 8 9 10 11
This
Thisindexed
indexed
expression
expressionrefers
refersto
to
The index of the first rainfall[2] the element at
the element at
position
position#2
#2
position in an array is 0.
ARRAY PROCESSING –
SAMPLE 1
Scanner scanner = new Scanner(System.in); The
Thepublic
public
double[] rainfall = new double[12]; constant
constantlength
length
returns the
returns the
capacity
capacityof
ofan
an
double annualAverage, array.
array.
sum = 0.0;
int[] number = { 2, 4, 6, 8 };
number.length 4
samplingData.length 9
monthName.length 12
VARIABLE-SIZE
DECLARATION
In Java, we are not limited to fixed-size array
declaration.
The following code prompts the user for the size
of an array and declares an array of designated
size:
Scanner scanner = new Scanner(System.in);
int size;
int[] number;
System.out.print("Size of an array:"));
size= scanner.nextInt( );
person
State
of
Memor
y After A
A is executed
CREATING AN OBJECT
ARRAY - 2
Code Person[ ] person;
Now
Nowthe
thearray
storing 20
arrayfor
for
Person
storing 20 Person
B
B person = new Person[20]; objects
objectsisiscreated,
the Person
created,but
objects
but
the Person objects
person[0] = new Person( ); themselves
themselvesare arenot
notyet
yet
created.
created.
perso
n
0 1 2 3 4 16 17 18 19
State
of
Memor
y After B
B is executed
CREATING AN OBJECT
ARRAY - 3
Code Person[ ] person; One
OnePerson
Personobject
objectisis
person = new Person[20]; created
createdand
andthethe
reference
reference to thisobject
to this object
C
C person[0] = new Person( ); isisplaced
placed in position0.
in position 0.
perso
n
0 1 2 3 4 16 17 18 19
State
of Perso
n
Memor
y After C
C is executed
Person ARRAY PROCESSING
– SAMPLE 1
Create Person objects and set up the person array.
person[i].setName ( name );
person[i].setAge ( age );
person[i].setGender( gender );
}
Person ARRAY PROCESSING
– SAMPLE 2
Find the youngest and oldest persons.
perso perso
n n
0 1 2 3 0 1 2 3
AA BB CC D
D AA CC D
D
Before A
A is executed After A
A is executed
OBJECT DELETION –
APPROACH 2 int delIdx = 1, last = 3; Delete
DeletePerson
PersonBBbyby
setting
setting the referencein
the reference
A
A person[delIdx] = person[last];
position 1 to the last
position 1 to the last
in
perso perso
n n
0 1 2 3 0 1 2 3
AA BB CC D
D AA D CC
D
Before A
A is executed After A
A is executed
Person ARRAY PROCESSING
– SAMPLE 3
Searching for a particular person. (Approach 2
Deletion is used. )
int i = 0;
if ( person[i] == null ) {
//not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");
} else {
//found - successful search
System.out.println("Found Ms. Latte at position " + i);
}
THE for-each LOOP
This new for loop is available from Java 5.0
The for-each loop simplifies the processing of
elements in a collection.
Here we show examples of processing elements
in an array.
int sum = 0; int sum = 0;
At A
A before searchMinimum
arrayOne A.
A. Local
Local
variable
variablenumber
number
does
does not exist
not exist
before the
before the
method
method
execution
execution
State
of
Memor
PASSING ARRAYS TO
METHODS - 2
Code public int searchMinimum(float[] number))
{
minOne
B
B
…
= searchMinimum(arrayOne);
While at C
C inside the method
arrayOne numbe C.
C. The
Thearray
array
r isis accessed
accessed
via
vianumber
number
inside
insidethe
the
method.
method.
State
of
Memor
PASSING ARRAYS TO
METHODS - 4
Code public int searchMinimum(float[] number))
{
minOne
…
= searchMinimum(arrayOne);
D
D }
At D
D after searchMinimum
arrayOne numbe
D.
D. The
Theparameter
parameterisis
r erased.
erased.The
The
argument
argumentstill
stillpoints
points
to the same object.
to the same object.
State
of
Memor
TWO-DIMENSIONAL ARRAYS
Two-dimensional arrays are useful in representing
tabular information.
DECLARING AND CREATING
A 2-D
Declaration
ARRAY
<data type> [][] <variable> //variation 1
<data type> <variable>[][] //variation 2
Creation
<variable> = new <data type> [ <size1> ][ <size2> ]
Example
payScaleTable
0 1 2 3 4
0
double[][] payScaleTable;
payScaleTable 1
= new double[4][5]; 2
3
ACCESSING AN ELEMENT
An element in a two-dimensional array is accessed
by its row and column index.
SAMPLE 2-D ARRAY
PROCESSING
Find the average of each row.
average[i] += payScaleTable[i][j];
}