[Go to site: main page, start]

0% found this document useful (0 votes)
1 views52 pages

AQuick Referenceof Java Programming Languagefor OOPApproach

This document serves as a quick reference guide for Java programming with a focus on object-oriented programming (OOP) concepts. It covers key OOP principles such as objects, classes, inheritance, polymorphism, and encapsulation, along with practical examples of arrays and predefined classes like Scanner and String. The document aims to equip students with the knowledge to understand and implement OOP in Java effectively.

Uploaded by

2024647544
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views52 pages

AQuick Referenceof Java Programming Languagefor OOPApproach

This document serves as a quick reference guide for Java programming with a focus on object-oriented programming (OOP) concepts. It covers key OOP principles such as objects, classes, inheritance, polymorphism, and encapsulation, along with practical examples of arrays and predefined classes like Scanner and String. The document aims to equip students with the knowledge to understand and implement OOP in Java effectively.

Uploaded by

2024647544
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Lesson Outcomes

At the end of the chapter, students should be able to:

✓ Understand the concept of object and class in OOP


✓ Define field and method in class
✓ Understand and use access modifier
✓ Understand and implement inheritance, polymorphism
✓ Understand how one class relate to one class
✓ Write program using OOP languages

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 1
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

A. INTRODUCTION TO OBJECT-ORIENTED PARADIGM


- OOP focuses on data structures with functionality or processing capability to those structures.
- Data structure definition and its defined processes are package together in some syntactic
structure, in which the structural definition and process implementation are hidden from the
program unit that uses it, which are called clients.
- The world around us is made up of objects such as people, automobiles, buildings, streets,
adding machines, papers, and so forth – each of these objects has the ability to perform certain
actions, and each of these actions has some effect on some of the other objects in the world.
- OOP is a programming methodology that views a program as similarly consisting of objects
that interact with each other by means of action.

Terminology of Object, Class and Methods

OOP has its own specialized terminologies which are object, class and methods.

▪ Object:
- Represent entity that has a state, exhibits some well-defined behaviour and has a unique
identity.
- Is a self-contained entity which has its own private collection of properties (i.e. data) and
methods (i.e. operation) that encapsulate functionality into a reusable and dynamically loaded
structure.
▪ Class:
- Represent a set or collection of objects that share a common structure and a common
behaviour.
▪ Field:
- Attribute of the class object.
- Two types:
i. Primitive, i.e. int, long, double etc.
ii. Reference data types (ADT), i.e. String
▪ Method:
- Represent the action of object
- Two types of methods:
i. User defined methods: constructor (default, normal, copy), destructor, storer/mutator,
retriever/accessor, processor and printer.
ii. Built-in methods

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 2
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Fundamentals characteristics of OOP are:

▪ Abstraction / Information Hiding:


- Separate the description of how to use a class from the implementation details, such as how
the class methods are defined.
- Information hiding avoids information overloading.
▪ Encapsulation
- Grouping software into a unit in such a way that it is easy to use because there is a well-
defined simple interface.
- The data and the actions are combined into a single item and the details of the implementation
are hidden, i.e. a class object.
- A programmer who uses a class does not need to know all the details of the implementation of
the class but need only know a much simpler description of how to use the class.
▪ Inheritance:
- Process by which a new class (derived class) is created from another class called the base class
(super class).
- A derived class automatically has all the instance variable s and all the methods that the base
class has, and can have additional methods and/or additional instance variables.
▪ Polymorphism
- Technique to allow changes being made in the method definition for derived classes and apply
those changes to the software written in the base class (super class).
- Types of polymorphism:
i. Static binding: Overloaded methods
ii. Dynamic binding: Overridden methods

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 3
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

B. ARRAY
- Array used to store a collection of data - more useful to think of an array as a collection of
variables of the same type.
- Declare single-dimensional array:
Syntax: elementType arrayName[] OR
ElementType[] arrayName
Example:
char[] alphabet;
int[] list;
double[] price;

- Create single-dimensional array:


Syntax: arrayName = new elementType[SIZE]
Example:
alphabet = new char[SIZE];
list = new int[SIZE];
price = new double[SIZE];

- Declare and create single-dimensional array:


Syntax: elementType[] arrayName = new elementType[SIZE]
Example:
char[] alphabet = new char[SIZE];
int[] list = new int[SIZE];
double[] price = new double[SIZE];
Example:
Java Program Segment
final int SIZE = 5;
int[] array = new int[SIZE];

Scanner read = new Scanner([Link]);

[Link]("Enter " + SIZE + " integer into array..");

for(int i=0; i<[Link]; i++)


{
[Link]("array[" + i + "] <- ");
array[i] = [Link]();
}

[Link]();
[Link]("Value entered into array");

for(int i=0; i<[Link]; i++)


{
[Link]("array[" + i + "] -> " + array[i]);

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 4
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

C. CLASSES AND OBJECT

▪ Object
- An object represents an entity in the real world that can be distinctly identified.
- An object has a unique identity, state and behaviour:
• State – also known as its properties or attributes is represented by data fields with their
current values. Example: Circle – radius, rectangle – width & height
• Behaviour – also known as its action is defined by methods. To invoke a method on an
object is to ask the object to perform an action. Example: circle – getArea().
- Objects of the same type are defined using a common class. Object is an instance of a class.

▪ Class
- Class is a template, blueprint or contract that defines what an objects data fields and methods
will be.
- A Java class uses variables to define data fields and methods to define actions.
- Class provides methods of a special type, known as constructors, which are invoked to create
new object.
- A constructor can performs any action, but constructors are designed to perform initializing
actions, such as initializing the data fields of objects.
- There are 2 types of classes:
i. Predefined classes, i.e. Scanner, String, Character, StringBuilder/StringBuffer,Math,
Arrays, File, and etc.- classes that contained predefined method.
ii. User-defined clasess – classes defined by programmer / user

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 5
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Predefined Classes

▪ Scanner Class
- Create object to read input from [Link] class ([Link] is a class refer to the standard
input device).

Example:
Program
/*This program demonstrates the use of Scanner Predefined
* Class
*/
Makes the Scanner class
package pkgCSC305; available to program

import [Link];

public class ScannerClass {

public static void main(String[] args) {


Scanner Scanner in = new Scanner([Link]);
class
[Link]("Enter any integer number : ");
Object int number = [Link]();
Method in Scanner
[Link]("You have entered " + number);

}
}

- new Scanner([Link])- creates an object of the Scanner type.


- Scanner in - declares that in is a variable whose type is Scanner.
- Scanner in = new Scanner([Link]) creates a Scanner object and assigns its
reference to the variable in.
- An object may invoke its methods. To invoke a method on object is to ask the object to
perform a task.
- List of methods for Scanner objects:
Method Description
nextByte() Reads an integer of the byte type
nextShort() Read an integer of the short type
nextInt() Read an integer of the int type
nextLong() Read an integer of the long type
nextFloat() Read an integer of the float type
nextDouble() Read an integer of the double type
next(); Read a string that ends before a whitespace character
nextLine(); Read a line of text (i.e. a string ending with the Enter key pressed).
To avoid input error, do not use after this method after all the other methods in
Scanner class

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 6
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ String Class
- Reference type for variables that represent string (sequence of characters)

Constructing a String

Example:
Program Output
/*This program demonstrates the use of Hello Roslan
* String Predefined Class
*/
package pkgCSC305;

public class PredefinedClass {

public PredefinedClass() {
}

public static void main(String[] args) {

String class String msg = "Hello ";


String name = "Roslan ";

[Link](msg + name);

} Class Method
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 7
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

String Comparison

Methods Effect
[Link](s2)→boolean Returns true if s1 equal to s2
[Link](s2)→boolean Returns true if s1 equal to s2 case insensitive
[Link](s2)→ int Returns 0 (s1 and s2 are indentical), < 0 (s1 less than s2), > 0
(s1 greater than s2)
[Link](s2)→ int Returns 0 (s1 and s2 are indentical), < 0 (s1 less than s2), and
> 0 (s1 greater than s2) case insensitive
[Link](prefix)→ boolean Returns true if s1 starts with the specified prefix
[Link](suffix) → boolean Returns true if s1 ends with the specified suffix

Example of string comparison:

i. [Link](s2 : String) : boolean and [Link](s2 : String) : boolean


Java Program Segment
String s1 = "Apple";
String s2 = "Apple";
String s3 = "aPPLe";

[Link]("s1 : Apple");
[Link]("s2 : Apple");
[Link]("s3 : aPPLe");

if ([Link](s2))
[Link]("Case sensitive : " + [Link](s2) + " : s1 and
s2 are identical");

if ([Link](s3))
[Link]("Case sensitive : " + [Link](s3) + " : s1 and
s3 are identical");

else
[Link]("Case sensitive : " + [Link](s3) + " : s1 and
s3 are not identical");

if ([Link](s3))
[Link]("Case insensitive : " + [Link](s3) +
" : s1 and s3 are identical");
Output
s1 : Apple
s2 : Apple
s3 : aPPLe
Case sensitive : true : s1 and s2 are identical
Case sensitive : false : s1 and s3 are not identical
Case insensitive : true : s1 and s3 are identical

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 8
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

ii. [Link](s2 : String) : int and [Link](s2 : String) : int


Java Program Segment
String s1 = "Orange";
String s2 = "oRaNGe";

[Link]("First Comparison : Case Sensitive");

if ([Link](s2) == 0)
[Link](s1 + " equal to " + s2);
else if ([Link](s2) > 0)
[Link](s1 + " greater than " + s2);
else
[Link](s1 + " less than " + s2);

[Link]();

[Link]("Second Comparison - Case insentive");

if ([Link](s2) == 0)
[Link](s1 + " equal to " + s2);
else if ([Link](s2) > 0)
[Link](s1 + " greater than " + s2);
else
[Link](s1 + " less than " + s2);
Output
First Comparison : Case Sensitive
Orange less than oRaNGe

Second Comparison - Case insentive


Orange equal to oRaNGe

iii. [Link](s2 : String) : boolean and [Link](s2 : String) : boolean


Java Program Segment
String pre = "App";
String suf = "nge";
String s1 = "Apple";
String s2 = "Orange";

if([Link](pre))
[Link](s1 + " starts with prefix " + pre);
else
[Link](s1 + " does not starts with prefix " + pre);

if ([Link](suf))
[Link](s2 + " ends with suffix " + suf);
else
[Link](s2 + " does not ends with suffix " + suf);
Output
Apple starts with prefix App
Orange ends with suffix nge

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 9
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

String Length, Characters, and Combining Strings

Methods Effect
[Link]() → int Returns the number
[Link](index) → char Returns the character at the specified index from this string
[Link](s2) → String Returns a new string that concatenates this string with string s1

Example:
Java Program Segment
String s1 = "Apple";
String s2 = "Sweet ";

int lengthS1 = [Link]();;

[Link]("The length of string " + s1 + " is " + lengthS1);

char c = [Link](0);
[Link]("Index 0 of " + s1 + " is character " + c);

String s3 = [Link](s1);
[Link](s2 + "+ " + s1 + " becomes " + s3);
Output
The length of string Apple is 5
Index 0 of Apple is character A
Sweet + Apple becomes Sweet Apple

String Length, Characters, and Combining Strings

Methods Effect
[Link](beginIndex) → String Returns the string’s substring that begins with the character at
the specified beginIndex and extends to the end of the string
[Link](beginIndex, endIndex) Returns the string’s substring that begins at the specified
→ String beginIndex and extends to the character at index endIndex – 1

Example:
Java Program Segment
String s1 = "Sweet Mango Cafe";
String s2 = [Link](6);
String s3 = [Link](0,11);

[Link]("String [Link](6) of " + s1 + " is " + s2);


[Link]("String [Link](0,11) of " + s1 + " is " + s3);
Output
String [Link](6) of Sweet Mango Cafe is Mango Cafe
String [Link](0,11) of Sweet Mango Cafe is Sweet Mango

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 10
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Obtaining substrings

Example:
Java Program Segment

String s1 = "Sweet Mango Cafe";


String s2 = [Link](6);
String s3 = [Link](0,11);

[Link]("String [Link](6) of " + s1 + " is " + s2);


[Link]("String [Link](0,11) of " + s1 + " is " + s3);

Output
String [Link](6) of Sweet Mango Cafe is Mango Cafe
String [Link](0,11) of Sweet Mango Cafe is Sweet Mango

Converting, Replacing, and Splitting Strings

Methods Effect
[Link]() → String Returns a new string with all characters converted to lowercase
[Link]() → String Returns a new string with all characters converted to uppercase
[Link]() →String Returns a new string with blank characters trimmed on both
side
[Link](oldChar, newChar) → Returns a new string that replaces the all matching characters
String in this string with the new character
[Link](oldString, Returns a new string that replaces the first matching substring
newString) → String in this string with the new string
[Link](oldString, newString) Returns a new string that replaces all matching substring in this
→ String string with the new string
[Link](delimiter) → String[] Returns an array of strings consisting of the substrings split by
the delimiter

Example:
Java Program Segment Output
String s = "Welcome";
String s2 = " Welcome ";
String s3 = "Wel#co#me";

[Link]([Link]()); welcome
[Link]([Link]()); WELCOME
[Link]([Link]()); Welcome
[Link]([Link]('e', 'A')); WAlcomA
[Link]([Link]("e", "AB")); WABlcome
[Link]([Link]("el", "AB")); WABcome

String[] tokens = [Link]("#");


for (int i=0; i<[Link]; i++)
[Link](tokens[i] + " "); Wel co me

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 11
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Finding a Character or Substring in a String

Methods Effect
[Link](ch) → int Returns the index of the first occurrences of ch in the string,
returns -1 if not matched
s1. indexOf (ch, fromIndex) → int Returns the index of the first occurrence of ch after fromIndex
in the string, returns -1 if not matched
s1. indexOf (str) → int Returns the index of the first occurrence of string s in this
string, returns -1 if not matched
[Link] (str, fromIndex) → int Returns the index of the first occurrence of string s in this
string after fromIndex, returns -1 if not matched
[Link](ch) →int Returns the index of the last occurrence of ch in the string,
returns -1 if not matched
[Link](ch, fromIndex) → int Returns the index of the last occurrence of ch before fromIndex
in this string, returns -1 if not matched
s1. lastIndexOf(str) → int Returns the index of the last occurence of string s, returns -1 if
not matched
s1. lastIndexOf(str, fromIndex) → Returns the index of the last occurrence of string s before
int fromIndex, returns -1 if not matched

Example:
Java Program Segment Return/Output
String s1 = "Welcome to Java";
[Link]([Link]('W')); 0
[Link]([Link]('e')); 4
[Link]([Link]('o',5)); 9
[Link]([Link]("come")); 3
[Link]([Link]("Java", 5)); 11
[Link]([Link]("java", 5)); -1

[Link]([Link]('W')); 0
[Link]([Link]('e')); 9
[Link]([Link]('o',5)); 4
[Link]([Link]("come")); 3
[Link]([Link]("Java", 5)); -1
[Link]([Link]("java", 5)); 11

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 12
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Conversion between Strings and Arrays

- String are not array but string can be converted into an array and vice versa

i. toCharArray
- to convert string to an array of characters

Example:
Java Program Segment Output
String text = "Java"; Java
[Link](text); arrayChar[0]: J
char[] arrayChar = [Link](); arrayChar[1]: a
for (int i=0; i <[Link]; i++) arrayChar[2]: v
[Link]("arrayChar[" + i + "]: " + arrayChar[3]: a
arrayChar[i]);

ii. [Link](srcBegin: int, srcEnd: int, dst: char[], dstBegin: int)


- To copy a substring of the string from index srcBegin to srcEnd-1 into a character array
dststarting from index dstBegin.

Example:
Java Program Segment Output
String src = "CSC305"; CSC305
char[] dst = {'I','T','C','3','0','5'};

[Link](0,3,dst,0);
[Link](dst);

iii. valueOf / String(char[])


- to convert an array of character to a String

Example:
Java Program Segment Output
String str = new String(new char[]{'J','a','v','a'}); Java
Java
String str2 = [Link](new char[]{'J','a','v','a'});

[Link](str);
[Link](str2);

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 13
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

iv. Converting Characters and Numeric Values to String


- The static valueOf method can be used to convert an array of characters into a string.
Methods Effect
[Link](c: char) → String Returns a string consisting of the character c
[Link](data: char[]) → String Returns a string consisting of the characters in the array
[Link](d: double) → String Returns a string representing the double value
[Link](f: float) → String Returns a string representing the float value
[Link](i: int) → String Returns a string representing the int value
[Link](l: long) → String Returns a string representing the long value
[Link](b: boolean) → String Return a string representing the boolean value

Problem: Checking Palindromes

- Reads the same forward and backwards


Java Program
package pkgCSC305;
import [Link].*;

public class Palindrome


{
public static void main(String[] args) {

Scanner read = new Scanner([Link]);


[Link]("Enter a string : ");
String s = [Link]();

if(isPalindrome(s))
{
[Link](s + " is a palindrome");
}
else
{
[Link](s + " is not a palindrome");
}
}
public static boolean isPalindrome(String s)
{
int low = 0;
int high = [Link]() - 1;
boolean isTrue = true;

while (low < high)


{
if ([Link](low) != [Link](high))
{
isTrue = false;
break;
}
low++;
high--;
}
return isTrue;
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 14
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ Character Class
- Enable primitive data value of character to be treated as object
- Example: Character character = new Character(‘a’);
Methods / Constructor Effect
[Link](value) Construct a character object with char value
[Link]() → char Returns the char value from this object
[Link](c2) → int Compares this character with another
[Link](c2)→ boolean Returns true if this character is equal another
[Link](c1) → boolean Returns true if the specified character is digit
[Link](c1) → boolean Returns true if the specified character is letter
[Link](c1) → boolean Returns true if the character is a letter or digit
[Link](c1) → boolean Returns true if the character is a lowercase letter
[Link](c1) → boolean Returns true if the character is an uppercase letter
[Link](c1) → char Returns the lowercase of the specified character
[Link](c1) → char Returns the uppercase of the specified character

Problem: Counting Each Letter in a String


Java Program
package pkgCSC305;
import [Link];

public class CountingLetters {

public static void main(String[] args)


{
Scanner input = new Scanner([Link]);

[Link]("Enter a string : ");

String s = [Link]();

int [] counts = countLetter([Link]());

for (int i=0; i<[Link]; i++)


{
if (counts[i] != 0)
[Link]((char)('a' + i) + " appears " +
counts[i] + ((counts[i] == 1) ? " time " : "
times "));
}
}

public static int[] countLetter(String s)


{
int [] counts = new int[26];

for (int i=0; i<[Link](); i++)


{
if([Link]([Link](i)))
counts[[Link](i) - 'a']++;
}

return counts;
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 15
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ StringBuilder/StringBuffer Class
- An alternative to the String class.
- Can be used whenever String is used.
- More flexible than String: add, insert, append new contents into a StringBuilder or a
StringBuffer.
- StringBuffer– methods for modifying buffer in it are synchronized.
- StringBuffer – more efficient if it is accessed by single task.
- Has three constructor andmore than 30 methods.

Example:
Java Program Output
StringBuilder strBuilder = new
StringBuilder("Hello,");

[Link](" ");
[Link]("welcome");
[Link](" ");
[Link]("to");
[Link](" ");
[Link]("Java");

[Link](strBuilder); Hello, welcome to Java

[Link](18, "HTML and ");

[Link](strBuilder); Hello, welcome to HTML and Java

[Link](22,30);

[Link](strBuilder); Hello, welcome to HTMLa

[Link](22);

[Link](strBuilder); Hello, welcome to HTML

[Link](18, 22, "Java");

[Link](strBuilder); Hello, welcome to Java

[Link](5, '!');

[Link](strBuilder); Hello! welcome to Java

[Link]();

[Link](strBuilder); avaJ ot emoclew !olleH

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 16
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Problem: Ignoring Nonalphanumeric Characters When Checking Palindromes

Java Program
package pkgCSC305;
import [Link];

public class Palindrome2 {

public static void main(String[] args)


{
Scanner read = new Scanner([Link]);

[Link]("Enter a string");
String s = [Link]();

[Link]("Ignoring nonalphanumeric characters...");


[Link]("Is " + s + " a palindrome ? " +
isPalindrome(s));
}

public static boolean isPalindrome(String s)


{
String s1 = filter(s);
String s2 = reverse(s1);

return [Link](s2);
}

public static String filter(String s)


{
StringBuilder strBuilder = new StringBuilder();

for (int i=0; i<[Link](); i++)


{
if([Link]([Link](i)))
[Link]([Link](i));
}

return [Link]();
}

public static String reverse(String s)


{
StringBuilder strBuilder = new StringBuilder(s);
[Link]();

return [Link]();
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 17
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ Math Class
- Contains the methods needed to perform basic mathematical function
- There are various class of methods under Math class, below are the few example:

i. Trigonometric Methods
Predefined methods Effect / Value Returned
[Link](x) Return the trigonometric sine of an angle in radians
[Link](x) Return the trigonometric cosine of an angle in radians
[Link](x) Return the trigonometric tangent of an angle in radians
[Link](x) Convert the angle in degrees to an angle in radians
[Link](x) Convert the angle in radians to an angle in degrees
[Link](x) Return the angle in radians for the inverse of sin
[Link](x) Return the angle in radians for the inverse of cos
[Link](x) Return the angle in radians for the inverse of tangent

ii. Exponent Methods


Predefined methods Effect / Value Returned
[Link](x) Return e raise to the power of x (ex)
[Link](x) Return the natural logarithm of x (ln(x) = loge(x))
Math.log10(x) Return the base 10 logarithm of x (log10(x))
[Link](x,y) Return a raised to the power of b (ab)
[Link](x) Return the square root of x (√𝑥 ) for x >= 0

iii. Rounding Methods


Predefined methods Effect / Value Returned
[Link](x) x is rounded up to its nearest integer. This integer is returned as a double
value
[Link](x) x is rounded down to its nearest integer. This integer is returned as a
double value
[Link](x) x is rounded to its nearest integer. If x is equally close to two integers,
the even one is returned as a double
[Link](x) x is rounded to its nearest integer

iv. min, max and abs methods


Predefined methods Effect / Value Returned
[Link](x,y) Return the lower value of x and y
[Link](x,y) Return the higher value of x and y
[Link](x) Return the absolute (positive) value of x

v. random method
Predefined methods Effect / Value Returned
(int) ([Link]()*x) Return a random number integer between 0 and x-1
x + (int) ([Link]()*y) Return a random number integer between x and (x+y)-1

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 18
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Example:
Java Program
package pkgCSC305;

public class RandomCharacter {

/**Generate a random character between ch1,and ch2*/


public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + [Link]() * (ch2 - ch1 + 1));
}

/**Generate a random lower case letter*/


public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}

/**Generate a random uppercase letter*/


public static char getUpperCaseLetter() {
return getRandomCharacter('A','B');
}

/**Generate a random digit character*/


public static char getRandomDigitCharacter() {
return getRandomCharacter('0','9');
}

/**Generate a random character*/


public static char getRandomCharacter() {
return getRandomCharacter('\u0000', '\uFFFF');
}

/**main() method*/
public static void main(String[] args) {
final int NUMBER_OF_CHARS = 175;
final int CHARS_PER_LINE = 25;

//print random characters between 'a' and 'z', 25 chars per


//line
for (int i=0; i<NUMBER_OF_CHARS; i++) {
char ch = [Link]();
if ((i+1) % CHARS_PER_LINE == 0)
[Link](ch);
else
[Link](ch);
}
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 19
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ Arrays Class
- [Link] class contains various static methods for sorting and searching arrays,
comparing arrays, and filling array elements.
- Static methods under Arrays class are:
• [Link]()
• sort the whole array or partial array
• [Link]()
• Search for a key in an array – the array must be presorted in increasing order.
• [Link]()
• to check whether two arrays are equal
• two arrays are equal if they have the same contents.
• [Link]()
• to fill in all or part of the array

i. [Link]()

example:
Java Program Output
int[] numbers = {6,4,2,3,5}; Before sort()
6 4 2 3 5
[Link]("Before sort()"); After sort()
for (int i=0; i<[Link]; i++) 2 3 4 5 6
[Link](numbers[i]+ " ");

[Link]();
[Link](numbers);
[Link]("After sort()");
for (int i=0; i<[Link]; i++)
[Link](numbers[i] + " ");

ii. [Link]()

example:
Java Program Output
int[] numbers = {6,4,2,3,5}; Before sort()
6 4 2 3 5
[Link]("Before sort()"); After sort()
for (int i=0; i<[Link]; i++) 2 3 4 5 6
[Link](numbers[i]+ " ");

[Link]();
[Link](numbers);
[Link]("After sort()");

for (int i=0; i<[Link]; i++)


[Link](numbers[i] + " ");

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 20
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

iii. [Link]()

example:
Java Program Output
int[] list1 = {2,3,5,7,11}; Array List1:
int[] list2 = {2,3,5,7,11}; 2 3 5 7 11
Array List2:
[Link]("Array List1: "); 2 3 5 7 11
for (int i=0; i<[Link]; i++)
[Link](" " + list1[i]); Array list1 and
list2 are equal
[Link]();
[Link]("Array List2: ");
for (int i=0; i<[Link]; i++)
[Link](" " + list2[i]);

[Link]();
[Link]();

if([Link](list1, list2))
[Link]("Array list1 and list2 are equal");

iv. [Link]()

example:
Java Program Output
int[] list1 = {1,2,3,4}; 3
3
[Link](list1, 3); 3
3
for (int i=0; i<[Link]; i++)
[Link](list1[i]);

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 21
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ File Class
- A File object encapsulates the properties of a file or a path but does not contain the methods
for creating a file or for reading/writing data from I/O file.
- The File Class is intended to provide an abstraction that deals with most of the machine-
dependent complexities of files and path names in a machine-independent fashion.
- The File Class contains the methods for obtaining File properties and for renaming and
deleting files.
- In order to perform I/O you need to create objects using appropriate Java I/O classes. The
objects contain the methods for reading/writing data from/to a file.
- Read/write strings and numeric values from/to a text file can be performed by using Scanner
and PrintWriter classes.

Predefined methods / Constructor Effect / Value Returned


+.File(pathName: String) Creates a File object for the specified path name. The path
name may be a directory or a file.
+.File(parent: String, child: String) Creates a File object for the child under the dirctory parent.
The child may be a file name or a subdirectory
+.File(parent: File, Child: String) Creates a File object for the child under the directory parent.
The parent is a File object. In the preceeding constructor, the
parent is a string.
+.exist(): boolean Returns true if the file or the directory represented by the File
object exists.
+.canRead(): boolean Returns true if the file represented by the File object exists and
can be written.
+.isDirectory(): boolean Returns true if the File object represents a directory.
+.isFile(): boolean Returns true if the File object represents a file.
+.isAbsolute: boolean Returns true if the file represented in the File object is hidden.
The exact definition of hidden is system dependent.
+.getAbsolutePath(): String Returns the complete absolute file or directory name
represented by the File object.
+.getCanonicalPath(): String Returns the same as getAbsolutePath() except that it removes
redundant names such as “.” And “..” from the path name.
+.getName(): String Returns the last name of the complete directory and file name
represented by the File object. For example: new
File(“c:\\book\\[Link]”).getName() returns [Link].
+.getParent(): String Returns the complete parent directory of the current directory
or the file represented by the File object. For example: new
File(“c:\\book\\[Link]”).getParent() returns c:\book.
+.lastModified(): long Returns the time that the file was last modified.
+.length(): long Return the size of the file, or 0 if it does not exist or if it is a
directory.
+.listFile(): File[] Returns the files under the directory for a directory File object.
+.delete(): boolean Delete this file. The method returns true if the deletion
succeeds.
+.renameTo (dest: File): boolean Renames this file. The method returns true if the operation
succeeds.

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 22
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Writing data using PrintWriter

- [Link] class can be used to create a file and write data to a text file.
- Create a PrintWriter object for a text file as follows:
printWriter output = new printWriter(fileName);

Predefined methods / Constructor Effect / Value Returned


+.PrintWriter(file:File) Creates a PrintWriter object for the specified file object.
+.PrintWriter(fileName: String) Creates a PrintWriter object for the specified file-name string.
+.print(s: String): void Writes a string to the file.
+.print(c: char): void Writes a character to the file.
+.print(cArray: char[]): void Writes an array of characters to the file.
+.print(i: integer): void Writes a integer to the file.
+.print(l: long): void Writes a long to the file.
+.print(f: float): void Writes a float to the file.
+.print(d: double): void Writes a double to the file.
+.print(b: boolean): void Writes a boolean to the file.
+.println() – prints a line separator
+.printf() – prints using specified format

Example:
Java Program
package pkgCSC305;

import [Link];

public class WriteData {

public static void main(String[] args) throws FileNotFoundException{


[Link] file = new [Link]("[Link]");

if ([Link]())
{
[Link]("File already exists");
[Link](0);
}

[Link] output = new [Link](file);


[Link]("Mohammad Mirza Rafiqi");
[Link](" Bin Rasidi");
[Link](3.78);
[Link]();
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 23
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

i. Reading data using Scanner


- [Link] used to read strings and primitive values from the console.
- A Scanner breaks it input into tokens delimited by whitespace characters.
- To read from the keyboard, you create a Scanner for [Link] as follows:
Scanner input = new Scanner ([Link]);
- To read from a file, you create a Scanner for a file as follows”
Scanner input = new Scanner (new File (fileName);

Predefined methods / Constructor Effect / Value Returned


+.Scanner(source: File) Creates a scanner that produces values scanned from the
specified file.
+.Scanner(source: String) Creates a scanner that produces values scanned from the
specified string.
+.close() Closes this scanner.
+.hasNext(): boolean Returns true if this scanner has more data to be read.
+.next(): String Returns next token as a string from this scanner.
+.nextLine(): String Returns a line ending with the line separator from this
scanner.
+.nextByte(): byte Returns next token as a byte from this scanner.
+. nextShort(): short Returns next token as a short from this scanner.
+.nextInt(): int Returns next token as an integer from this scanner.
+.nextLong(): long Returns next token as a long from this scanner.
+.nextFloat(): float Returns next token as a float from this scanner.
+.nextDouble(): double Returns next token as a double from this scanner.
+.useDelimiter(patter: String): Scanner Set this scanner’s delimiting pattern and returns this
scanner.

Example:
Java Program
import [Link];
import [Link].*;

public class ReadData {


public static void main(String[] args) throws IOException {
File file = new File("[Link]");
Scanner input = new Scanner(file);

while ([Link]()){
String firstName = [Link]();
String secondName = [Link]();
String thirdName = [Link]();
String fourthName = [Link]();
String lastName = [Link]();
float score = [Link]();

[Link](firstName + " " + secondName + " " +


thirdName + " " + fourthName + " " + lastName + " "
+ score);
}

[Link]();
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 24
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

User-Defined Classes

▪ Constructing Objects Using Constructors


- A constructor must have the same name as the class itself
- Constructors do not have return type – not even void
- Constructors are invoked using the new operator when an object is created. Constructors play
the role of initializing objects.
- A class normally provides a constructor without arguments (i.e. Circle()). Such constructor is
referred to as a no-arg or no-argument constructor.
- A class may be defined without constructors. Default constructor is provided automatically
only if no constructors are explicitly defined in the class.

▪ Accessing Objects via Reference Variables


- Newly created objects are allocated in the memory. The can be accessed via reference
variables.
- Reference variables are declared using the following syntax:
className objectReferenceVariable;
- Creates an object and assigns its reference to objectReferenceVariable:
objectReferenceVariable = new className();
- The following syntax is a declaration of an object reference variable, the creation of an object
and the assigning of an object reference to the variable:
className objectReferenceVariable = new className();
Example:
Circle c = new Circle();
- The variable c holds a reference to Circle object.

▪ Accessing an Object’s Data and Methods


- After an object is created, its data can be accessed and its method invoked using the dot
operator (.) also known as the object member access operator:
• [Link] – reference a data field in the object.

• [Link](arguments) – invokes method on the object.


- Example:
• [Link]
• References the radius in c1
• data field radius is referred to as an instance variable, because it is independent on a
specific instance.

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 25
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

• [Link]()
• Invokes the getArea() method on c1. Methods are invoked as operations on objects.
• Method getArea() is referred to as instance method, because it can be invoke only on
a specific instance.
• The object on which an instance method is invoked is called a calling object.

Example 1: Defining Classess, Creating Objects And Accessing Object’s Data and Methods

Java Program
package pkgCSC305;

class Circle{

double radius; // field or attribute

Circle(){ //constructor method with default radius


radius = 1.0;
}

Circle(double newRadius){ //constructor with a specified radius


radius = newRadius;
}

double getArea(){
return radius * radius * [Link];
}
}

public class TestCircle {

public static void main(String [] args){

Circle c1 = new Circle(); //create a circle with radius 1.0


[Link]("The area of the c1 of radius " + [Link] + " is
" + [Link]());

Circle c2 = new Circle(25); //create a circle with radius 25


[Link]("The area of the c2 of radius " + [Link] + " is
" + [Link]());

[Link] = 100; // modify circle radius for object c2


[Link]("The area of the c2 of radius " + [Link] + " is
" + [Link]());

c2 = new Circle(32); //create a circle with radius 25


[Link]("The area of the c2 of radius " + [Link] + " is
" + [Link]());
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 26
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ Static Variables, Constants, and Methods


- Static variable:
• In order for the instances of a class to share data, use static variables, also known as class
variables.
• Static variables store values for the variables in a common memory location.
• Because of this common location, if one changes the value of a static variable, all objects
of the same class are affected.
• Declaration:
static int numberOfOjbect;

- Static method:
• Same as static variables.
• Static methods can be called without creating an instance of the class.
• Definition:
static int getNumberObject() { return numberOfObject; }

- Declare constant:
• final static double PI = 3.1412;

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 27
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Example:
Java Program
package pkgCSC305;

public class TestCircle2 {

public static void main(String[] args) {


[Link]("Before creating objects");
[Link]("The number of Circle objects is " +
[Link]);
[Link]("Default Area : "
+ new Circle().getArea());

Circle2 c1 = new Circle2();

[Link]("\nAfter creating c1");


[Link]("c1: radius(" + [Link] + ") and number of
Circle objects " + [Link]);
[Link]("Area of c1 " + [Link]());

Circle2 c2 = new Circle2(5);


[Link] = 9;

[Link]("\nAfter creating c2 and modifying c1");


[Link]("c1: radius(" + [Link] + ") and number of
Circle objects " + [Link]);
[Link]("Area of c1 " + [Link]());
[Link]("c2: radius(" + [Link] + ") and number of
Circle objects " + [Link]);
[Link]("Area of c2 " + [Link]());
}
}

class Circle2{

double radius;
static int numberOfObjects = 0;

Circle2()
{
radius = 1.0;
numberOfObjects++;
}

Circle2(double newRadius)
{
radius = newRadius;
numberOfObjects++;
}

static int getNumberObjects()


{
return numberOfObjects;
}

double getArea()
{
return radius * radius * [Link];
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 28
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ Visibility Modifiers (visibility increases: private → none → protected → public)


- public: public modifier means its visibility can be used for classes, methods and data fields
to denote that they can be accessed from any other classes.
- If there is no visibility modifier used, then by default the classes, methods and data fields are
accessible by any class in the same package. This is known as package-private or package-
access.
- package: packages can be used to organize classes. To do so, you need to add the following
line as the first noncomment and nonblank statement in the program:
package packageName;
Example:
package pkgCSC305;
- private: private modifier makes method and data fields accessible only from within its own
class.

package p1; package p1; package p2;

public class C1 { public class C2 { public class C3 {


public int x; void aMethod() { void aMethod() {
int y; C1 ob = new C1(); C1 ob = new C1();
private int z; Can access ob.x; Can access ob.x;
Can access ob.y; Cannot access ob.y;
public void m1() {} Cannot access ob.z; Cannot access ob.z;
void m2(){}
private void m3(){} Can invoke ob.m1(); Can invoke ob.m1();
} Can invoke ob.m2(); Cannot invoke ob.m2();
Cannot invoke Cannot invoke
ob.m3(); ob.m3();

} }
} }

- protected: to allow subclasses to access fields or methods defined in the superclass, but not
allow non-sub classes to access the field and methods.

Modifier on Accessed from Accessed from Accessed from a Accessed from a


Members in a the same class the same subclass different
class package package
public / / / /
protected / / / -
default (none) / / - -
private / - - -

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 29
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ Data Field Encapsulation


- To prevent direct modification of data fields, you should declare the data fields private,
using the private modifier. This is known as data field encapsulation.
- A private data field cannot be accessed by an object from outside the class that defines the
private field. But often a client needs to retrieve and modify a data field.
- To make data field accessible, provide a get method to return its value. To enable a private
data field to be updated, provide a set method to set a new value.

Example:
Java Program
package pkgCSC305;

public class TestCircle3 {

public static void main(String[] args){

Circle3 c1 = new Circle3(5.0);

[Link]("The area of the circle of radius " +


[Link]() + " is " + [Link]());

[Link]([Link]()* 1.1);

[Link]("The area of the circle of radius " +


[Link]() + " is " + [Link]());

[Link]("The number of object created is " +


[Link]());
}
}

class Circle3{

private double radius = 1; //encapsulate radius;


private static int numberOfObjects = 0; //encapsulate numberOfObjects

public Circle3(){numberOfObjects++;}

public Circle3(double newRadius){


radius = newRadius;
numberOfObjects++;
}

public double getRadius(){return radius;}

public void setRadius(double newRadius){


radius = (newRadius >= 0) ? newRadius : 0;
}

public static int getNumberOfObjects(){return numberOfObjects;}

public double getArea(){


return [Link](radius, 2) * [Link];
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 30
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ Passing Objects to Methods


- like passing an array, passing an object is actually passing the reference of the object.

Example:
Java Program
package pkgCSC305;

class Circle4{
private double radius = 1; //encapsulate radius;
private static int numberOfObjects = 0; //encapsulate numberOfObjects

public Circle4(){numberOfObjects++;}
public Circle4(double newRadius){
radius = newRadius;
numberOfObjects++;
}
public double getRadius(){return radius;};
public void setRadius(double newRadius){
radius = (newRadius >= 0) ? newRadius : 0;
}
public static int getNumberOfObjects(){return numberOfObjects;}
public double getArea(){return [Link](radius, 2) * [Link];}
}

public class PassObject {

public static void printAreas(Circle4 c, int times){


[Link]("Radius \t\tArea");
while (times >= 1)
{
[Link]([Link]() + "\t\t" + [Link]());
[Link]([Link]()+1);
times--;
}
}

public static void main (String [] args){


Circle4 myCircle = new Circle4(1);

int n = 5;
printAreas(myCircle,n);

[Link]("\nRadius is " + [Link]());


[Link]("n is " + n); }

Output
Radius Area
1.0 3.141592653589793
2.0 12.566370614359172
3.0 28.274333882308138
4.0 50.26548245743669
5.0 78.53981633974483

Radius is 6.0
n is 5

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 31
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ Array of Objects
- The following statement declares and creates array of 10 obj object.
ClassName[] obj = new ClassName[size];
Example:
Circle[] circleArray = new Circle[10];
- To initialize thecircleArray, you can use a for loop like this one:
for (int i = 0; i <[Link]; i++) {
circleArray[i] = new Circle();
}

Example:
Java Program
package pkgCSC305;

class Circle5{
private double radius = 1; //encapsulate radius;
private static int numberOfObjects = 0; //encapsulate numberOfObjects

public Circle5(){numberOfObjects++;}
public Circle5(double newRadius){
radius = newRadius;
numberOfObjects++;
}
public double getRadius(){return radius; }
public void setRadius(double newRadius){
radius = (newRadius >= 0) ? newRadius : 0;
}
public static int getNumberOfObjects(){return numberOfObjects;}
public double getArea(){return [Link](radius, 2) * [Link];}
}

public class TotalArea {

public static void main(String[] args){


Circle5[] circleArray;
circleArray = createCircleArray();
printCircleArray(circleArray);
}

public static Circle5[] createCircleArray(){


Circle5[] circleArray = new Circle5[5];

for (int i = 0; i < [Link]; i++)


circleArray[i] = new Circle5([Link]() * 100);

return circleArray;
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 32
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

public static void printCircleArray(Circle5[] circleArray){


[Link]("%-30s%-15s\n", "Radius", "Area");
for (int i = 0; i < [Link]; i++) {
[Link]("%-30s%-15s\n",
circleArray[i].getRadius(), circleArray[i].getArea());
}

[Link]("-------------------------------------------
-------------");
[Link]("%-30s%-15s\n", "The total area of circle is
", sum(circleArray));
}
public static double sum(Circle5[] circleArray){
double sum = 0;
for (int i = 0; i < [Link]; i++)
sum += circleArray[i].getArea();
return sum;
}

}
Output
Radius Area
40.43061764438477 5135.356814405086
94.62579335893402 28129.948699229713
89.72514484194619 25291.710896656983
97.32597575533629 29758.25121328157
92.30989550748046 26769.877966284428
--------------------------------------------------------
The total area of circle is 115085.14558985777

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 33
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

D. THINKING IN OBJECT

▪ Immutable Objects and Classes


- Content of object which cannot be changed once the object is created.
- If the class is a mutable, then all its data filed must be private and it cannot contain public set
methods for any data fields.
- For a class to be immutable, it must meet the following requirements:
• all data fields private;
• no mutator methods;
• no accessor method that returns a reference to a data field that is mutable.

Example:
Java Program
public class Student{

private int id;


private String name;

public Student (int ssn, String newName){//Normal constructor


id = ssn;
name = newName;
}
public int getID(){ return id; }
public String getName() { return name; }
}

▪ Acessor and Mutator Methods


- Accessor method: allow you to obtain the data from a class object.
- Mutator method: allow you to change the data in a class object.

Example:
Java Program
public class Student{
private int id;
private String name;
public student(){ // default constructor
id = 0;
name = " ";
}
public Student (int ssn, String newName){// Normal constructor
id = ssn;
name = newName;
}
public int getID(){ return id; } // Accessor method
public String getName() { return name; }// Accessor method
public void setName(String newName) { name = newName;}// mutator
// method
public void setId (int newId) { id = newId; }// mutator method

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 34
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ The this Reference


- The this keyword is the name of a reference that refers to a calling object itself.
- One of its common uses is to reference a class’s hidden data fields.
- A hidden static variable can be accessed simply by using the [Link]
reference. A hidden instance variable can be accessed by using the keyword this.

Example:
Java Program
package pkgCSC305;

public class TheThis {

public static void main(String [] args){

Foo f1 = new Foo(1,1);


[Link]("i = " + [Link]());
[Link]("this.j = " + [Link]());

Foo f2 = new Foo();


[Link](2);
[Link](2);

[Link]("i = " + [Link]());


[Link]("this.j = " + [Link]());

Foo f3 = new Foo();


[Link]("i = " + [Link]());
[Link]("this.j = " + [Link]());
[Link](Foo.i + " " );
[Link](f3.getJ2() + " " );

}
}
class Foo {
static int i = 0;
int j = 0;

public Foo(){}
public Foo(int a, int b){
i = a;
j = b;
}
public int getI(){return i;}
public int getJ(){return this.j;}
public int getJ2(){return j; }
void setI(int a) {i = a;}
void setJ(int b) {this.j = b;}
}
Output
i = 1
this.j = 1
i = 2
this.j = 2
i = 2
this.j = 0
2
0

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 35
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

E. INHERITANCE AND POLYMORPHISM

▪ Inheritance: Is an important and powerful feature in Java for reusing software.


- Superclasses: also referred to as a parent class or a base class.
- Subclass: as extended class or derived class from superclass. It inherits accessible data fields
and methods from its superclass and may also add new data fields and methods.
• Subclass is not a subset of its superclass. In fact, a subclass usually contains more
information and methods than its superclass.
• Privated data fields in a superclass are not accessible outside the class; therefore they
cannot be used directly in a subclass. They can, however, be accessed/mutated through
public accessor/mutator if defined in the superclass.
• Not all is-a relationship should be modeled using inheritance.
• Inheritance is used to model the is-a relationship. Do not blindly extend a class just for the
sake of reusing methods. A subclass and its superclass must have the is-a relationship.

▪ Using the super Keyword


- The keyword super refers to the superclass of the class in which super appears.
- It can be used in two ways:
• To call a superclass constructor
• To call a superclass method
- The syntax to call a superclass constructor is : super(); or super(parameter);

- The following points regarding inheritance were worthwhile to note:

• A subclass is not a subset of its superclass. Usually, a subclass contains more information and
methods that its superclass.
• Private data fields in a superclass are not accessible outside the class. Therefore they cannot be
used directly in a subclass. They can be accessed/mutated through public accessor/mutator if
defined in the superclass.
• Not all is-a relationship should be modeled using inheritance.
• Inheritance is used to model the is-a relationship. A subclass and its superclass must have the
is-a relationship.
• Java does not allow multiple inheritance (C++ allow multiple inheritance).

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 36
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Example:
Java Program (Base Class)
package pkgCSC305;

public class GeometricObject1 {


private String color = "White";
private boolean filled;
private [Link] dateCreated;

//default constructor
public GeometricObject1(){ dateCreated = new [Link]();}

// normal constructor
public GeometricObject1(String color, boolean filled){
dateCreated = new [Link]();
[Link] = color;
[Link] = filled;
}

public String getColor(){ //accessor


return color;
}

public void setColor(String color) { //mutator


[Link] = color;
}

public boolean isFilled(){ //accessor


return filled;
}

Public void setFilled(boolean filled){ //mutator


[Link] = filled;
}

public [Link] getDateCreated(){


return dateCreated;
}

public String toString(){


return "created on " + dateCreated + "\ncolor: " + color + "
and filled : " + filled;
}
}

Java Program (Sub Class)


package pkgCSC305;

public class Circle7 extends GeometricObject1{


private double radius;

public Circle7(){}

public Circle7(double radius){


[Link] = radius;
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 37
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

public Circle7(double radius, String color, boolean filled){


[Link] = radius;
setColor(color);
setFilled(filled);
}

public double getRadius(){


return radius;
}

public void setRadius(double radius){


[Link] = radius;
}

public double getArea(){


return [Link](radius, 2) * [Link];
}

public double getDiameter(){


return 2 * radius;
}

public double getPerimeter(){


return 2 * radius * [Link];
}

public void printCircle(){


[Link]("The circle is created " + getDateCreated()
+ " and the radius is " + radius);
}
}

Java Program (Main Class)


package pkgCSC305;

public class TestCircleRectangle {

public static void main(String[] args) {

Circle7 circle = new Circle7(1);


[Link]("A circle " + [Link]());
[Link]("A circle " + [Link]());
[Link]("A circle " + [Link]());
[Link]("A circle " + [Link]());
}
}
Output
A circle created on Sat Jul 21 18:24:52 SGT 2012
color: White and filled : false
A circle 1.0
A circle 3.141592653589793
A circle 2.0

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 38
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

▪ Polymorphism: Is the capability of an action or method to do different things based on the object
that is acting upon. This is the third basic principle of OOP. There are THREE types of
polymorphism:
i. Overloaded Methods: Are methods with the same name signature but either a different
number of parameters or different types in the parameter.

Example:
Java Program
public class Test {
public static void main(String[] args){
A a = new A();
a.p(10);
a.p(10.0);
}
}

class B {
public void p(double i) {
[Link](i * 2);
}
}

class A extends B {
public void p(int i) {
[Link](i);
}
}

ii. Overriden Methods: Are methods that are defined within an inherited or subclass. They
have the same signature and the subclass definition is used.

Example:
Java Program
public class Test {
public static void main(String[] args){
A a = new A();
a.p(10);
a.p(10.0);
}
}

class B {
public void p(double i) {
[Link](i * 2);
}
}

class A extends B {
public void p(double i) {
[Link](i);
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 39
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

iii. Dynamic method binding:Is the ability of a program to resolve references to subclass
methods at runtime.

Example:
Java Program
package pkgCSC305;

public class DynamicBinding {


public static void main(String[] args){
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}

public static void m(Object x){


[Link]([Link]());
}
}

class GraduateStudent extends Student{}

class Student extends Person {


public String toString(){
return "Student";
}
}
class Person extends Object{
public String toString(){
return "Person";
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 40
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

F. OBJECT COMPOSITION
- An object can contain another object. The relationship between the two is called composition.
- Composition is actually a special case of the aggregation relationship. Aggregation model has-
a relationship and represents an ownership between two objects.
- The owner is called an aggregating object and its class an aggregating class.
- The subject object is called an aggregated object and its class an aggregated class.

Aggregated Class Aggregating Class Aggregated Class


public class Name { public class Student { public class Address {
.... private Name name; ....
} private Address add; }
....
}

Example:
Java Program
package pkgCSC305;

class Engine {
public String start() {return "Engine Start";}
public String rev() {return "Engine Reverse";}
public String stop() {return "Engine Stop";}
}

class Wheel {
public int inflate(int psi) {return psi;}
}

class Window {
public String rollup() {return "Window: Rool up";}
public String rolldown() {return "Window: Roll Down";}
}

class Door {
public Window window = new Window();
public String open() {return "Door: Open";}
public String close() {return "Door: Close";}
}

Public class Car {


public Engine engine = new Engine();
public Wheel[] wheel = new Wheel[4];
public Door
left = new Door(),
right = new Door(); // 2-door
public Car() {
for(int i = 0; i < 4; i++)
wheel[i] = new Wheel();
}
public static void main(String[] args) {
Car car = new Car();
[Link]([Link]());
[Link]("PSI for Wheel[0]: " +
[Link][0].inflate(72));
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 41
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

G. ABSTRACT CLASSES AND INTERFACES


- Abstract class: superclass that cannot have any specific instances.
- Abstract method: method in abstract class that have no implementation. The implementation
detail is in subclass.

Example:
Java Program (Abstract Class)
package pkgCSC305;

public abstract class GeometricObject {

private String color = "White";


private boolean filled;
private [Link] dateCreated;

public GeometricObject(){ dateCreated = new [Link]();}


public GeometricObject(String color, boolean filled){
dateCreated = new [Link]();
[Link] = color;
[Link] = filled;
}

public String getColor(){


return color;
}

publicvoid setColor(String color) {


[Link] = color;
}

publicboolean isFilled(){
return filled;
}

publicvoid setFilled(boolean filled){


[Link] = filled;
}

public [Link] getDateCreated(){


return dateCreated;
}

public String toString(){


return "created on " + dateCreated + "\ncolor: " + color + "
and filled : " + filled;
}

Public abstract double getArea(); //abstract method


public abstract double getPerimeter();
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 42
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Java Program (Sub Class)


package pkgCSC305;

public class Circle8 extends GeometricObject{


private double radius;

public Circle8(){}

public Circle8(double radius){


[Link] = radius;
}

public Circle8(double radius, String color, boolean filled){


[Link] = radius;
setColor(color);
setFilled(filled);
}

public double getRadius(){


return radius;
}

public void setRadius(double radius){


[Link] = radius;
}

public double getArea(){


return [Link](radius, 2) * [Link];
}

publicdouble getDiameter(){
return 2 * radius;
}

public double getPerimeter(){


return 2 * radius * [Link];
}

public void printCircle(){


[Link]("The circle is created " + getDateCreated()
+ " and the radius is " + radius);
}
}

Java Program (Sub Class)


package pkgCSC305;

public class TestGeometricObject {

public static void main(String[] args){


GeometricObject geoObject = new Circle8(5);

displayGeometricObject(geoObject);
}
public static void displayGeometricObject(GeometricObject object){
[Link]("The area is " + [Link]());
[Link]("The perimeter is " +
[Link]());
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 43
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

- Interface: is a classlike construct that contains only constants and abstract methods. It is
similar to abstract class, but its intent to specify common behaviour for objects.
- Example of interface:
public interface Edible {
public abstract String howToEat();
}
Example:
Java Program (Sub Class)
package pkgCSC305;

class Animal {}

class Chicken extends Animal implements Edible{


public String howToEat() {
return "Chicken: Fry it";
}
}

class Tiger extends Animal {}

abstract class Fruit implements Edible {}

class Apple extends Fruit {


public String howToEat() {
return "Apple: Make apple cider";
}
}

class Orange extends Fruit {


public String howToEat() {
return "Orange: Make orange juice";
}
}

interface Edible{
public abstract String howToEat();
}

public class TestEdible {

public static void main(String[] args) {


Object[] objects = {new Apple(), new Orange(), new Chicken(),
new Tiger()};
for (int i = 0; i < [Link]; i++)
if (objects[i] instanceof Edible)
[Link](((Edible)
objects[i]).howToEat());
}
}

Output

Apple: Make apple cider


Orange: Make orange juice
Chicken: Fry it

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 44
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

REFERENCES:

Sebesta, W. R., (2010). Concepts of Programming Languages, Ninth Edition. Pearson

Liang, D. Y., (2011).Introduction to Java Programming. Pearson

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 45
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

EXAMPLES OF PAST EXAM QUESTION

[Mar2012-B3]
public abstract class Article{

private String title;


protected double price;
protected String publisher;
protected String writer_name;

public Article(String t, double pr, String p) {


title = t;
publisher = p;
price = pr;
}

public String getTitle() {return title;}


public double getPrice() {return price;}
public String getName() {return writer_name;}

public String toString() {


return "Article title : " + title + "\nPrice : " + price +
"\nWrite Name : " + writer_name;
}

public abstract int getLength();


public abstract double calcPrice();
}

a. Derive two subclasses named magazine and CD. These subclasses should have getLength() and
calcPrice() methods.
Magazine: adds a page count (number of pages) and cost per page.
CD: adds a playing time (in minutes) and cost per minute.
getLength will return the number of pages or playing times (in minutes).
calcPrice will calculate the cost of book (number of pages * cost per pages) and the cost for
CD is number of minutes * cost per minute and set its price in the Article class.
getCost will return the price.
Both subclasses have their normal constructors and a toString method each.

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 46
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

Answer:
import [Link];
public class CD extends Article {
private int time;
private double cost;

public CD(String t, double p, String au, int m, double c)


{
super(t,p, au);
time = m;
cost = c;
}

public int getLength(){


return time;
}

public double calcPrice(){


price = cost * time;
return price;
}

public String toString() {


[Link] dc = new DecimalFormat("0.00");
return [Link]() + "\nPlaying time (minutes) : " + time
+ "\n Cost per minute: RM" + [Link](cost);
}

public class Magazine extends Article {


private int page;
private double cost;

public Magazine(String t, double p, String au, int m, double c)


{
super(t,p, au);
page = m;
cost = c;
}

public int getLength(){


return page ;
}

public double calcPrice(){


price = cost * page;
return price;
}

public String toString() {


[Link] dc = new DecimalFormat("0.00");
return [Link]() + "\nPlaying time (minutes) : " + page
+ "\n Cost per minute: RM" + [Link](cost);
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 47
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

b. Write a complete application class called ArticleApp that performs each of the following in
sequence:
• Read the total number of published article.
• Declare an array of object to hold the published materials using polymorphism.
• For each published material, read in the type of publication (Magazine or CD) and the
properties.

Answer:
import [Link].*;
import [Link].*;

public class ArticleApp {

public static void main(String[] args) {


int b = 0;
double total = 0;

int ask = [Link]([Link]("Enter number


of Artcile :"));
Article AA[] = new Article[ask];

for (int i=0; i<[Link];i++)


{
String a = [Link]("Enter the Title");
String type = [Link]("Enter type of
Article");
char ty = [Link](0);
String c = [Link]("Enter the Write Name");

if (ty == 'm' || ty == 'M')


{
String j = [Link]("Enter the
number of pages : ");
int w = [Link](j);
String h = [Link]("Enter the cost
per pages: RM");
double m = [Link](h);
double f = 0;
AA[i] = new Magazine(a,f,c,w,m);
}

if (ty == 'c' || ty == 'C')


{
String j = [Link]("Enter the playing
time (minutes) : ");
int w = [Link](j);
String h = [Link]("Enter the cost
per minutes: RM");
double m = [Link](h);
double f = 0;
AA[i] = new Magazine(a,f,c,w,m);
}
AA[i].calcPrice();
}
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 48
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

[Sept2011-B3]
Given the following diagram are the class of Patient as super class and InPatient and OutPatient as
subclasses.

Answer the following questions based on the above diagram.

a) Write the normal constructor for both classes.


Answer:
InPatient(String patientID, String patientName, String patientGender, String
patientOccupation, String dateOfWarded, int dayOfWarded)
{
super(patientID, patientName, patientGender, patientOccupation);
[Link] = dateOfWarded;
[Link] = dayOfWarded;
}

OutPatient String patientID, String patientName, String patientGender, String


patientOccupation, String dateOfAppointment, boolean referToSpecialist)
{
super(patientID, patientName, patientGender, patientOccupation);
[Link];
this. referToSpecialist;
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 49
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

b) Write the definition for abstract method from both subclasses. Given for out patient the charges
will be incurred when the patient will be referred to specialist doctor. The charges are RM20. For
in patient, charges depend on the number of days warded. The charges are RM 10 per day.

Answer:
double calcCharges()
{
return getDayOfWarder * 10;
}

double calcCharges()
{
double charge = 0;
if (getRefSpecialist() == true)
charges = 20;
return charge;
}

c) Write a program fragment to determine total charges that have been collected from all patients.
Answer:
double totalCharge = 0;
for (int i=0; i<[Link]; i++)
totalCharge = totalCharge + patient[i].calcCharge();
[Link](“\nTotal charges that have been collected, RM”) <<
totalCharge.

d) Count number of patient who have been warded more than 5 days.
Answer:
int count=0;
for (int j=0; j<[Link]; j++)
{
if(patient[j] instanceOf InPatient) {
InPatient temp = (InPatient) patient[j];
if ([Link]() > 5)
count++;
}
}

[Link](“\nNumber of patients warded for more than 5 days ” + count);

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 50
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

e) Lis all males’s name that has been referred to the specialist doctor.
Answer:
for (int i=0; i<[Link]; i++)
{
if (patient[j] instanceOf OutPatient) {
OutPatient temp = (OutPatient) patient[j];
if (([Link]() == true) &&
([Link]().equals(“male”)))
[Link](“\nName : ” +[Link]());
}
}

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 51
A Quick Reference of Java Programming Language for Object Oriented Programming Approach

TUTORIAL

Roslan Bin Sadjirin


Centered of Study for Computer and Mathematical Sciences, UiTM Pahang 52

You might also like