VOKASIONAL
KEMENTERIAN PENDIDIKAN MALAYSIA
ARAS 5 & 6, BLOK E14, KOMPLEKS E,
PUSAT PENTADBIRAN KERAJAAN PERSEKUTUAN
KERTAS PENERANGAN
(INFORMATION SHEET)
TAJUK/TITLE :
BASIC OF ARRAY, STRING MANIPULATION AND CLASSES
TUJUAN / PURPOSE :
Kertas penerangan ini adalah bertujuan menerangkan mengenai :
menerangkan mengenai konsep tatasusunan (array)
menerangkan mengenai tatasusunan satu dimensi (One-Dimensional Array)
menerangkan mengenai tatasusunan dua dimensi (Two-Dimensional Array)
menerangkan mengenai string declaration
menerangkan mengenai string function
menerangkan sintaksis untuk mencipta kelas
menerangkan sintaksis untuk mencipta objek
menerangkan sintaksis untuk ’Method Call by Value and Reference’
menerangkan sintaksis untuk ’Overriding and Overloading’
Muka Surat / Page : 2
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
PENERANGAN / INFORMATION :
1. Array Fundamentals
80 90 100 70
1 baris
beberapa lajur
Syntax :
<jenis data> <pembolehubah>[ ] ={ nilai1, nilai2, nilai3 };
Example :
int markah[ ] = {80, 88, 90, 60};
Syntax :
<jenis data> <pembolehubah>[ ] = new <jenis data> [saiz tatasusunan];
Contoh :
int markah[ ] = new int[4];
i) Elemen pertama :
System.out.println(“Markah = “+markah[0]);
Tulis satu aturcara untuk menerima nama dan berat 5 orang pelajar dan menyimpan data
tersebut ke dalam dua tatasusunan yang berlainan. Paparkan data tersebut di akhir program,.
import java.io.*;
class Pelajar
{
public static void main (String args[]) throws IOException
{
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
int j;
String str;
String name[]= new String[5];
double weight[]=new double[5];
/*** menerima serta menyimpan nama dan berat 5 orang pelajar ke dalam
tatasusunan ***/
System.out.print("Enter weight:");
str = stdin.readLine();
weight[j] = Double.parseDouble(str);
Muka Surat / Page : 4
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
} //end for
Baris 0 80 88 90
Baris 1 60 70 95
Baris 2 55 45 35
Baris 3 100 90 80
Example :
Lajur 0
int markah[ ][ ] = {{80, 88,90}, {60, 70, 95}, {55, 45, 35},{100, 90, 80 }};
Baris 0
Lajur 0 Lajur 1
Baris 0
Muka Surat / Page : 5
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
Syntax :
<jenis data> <pembolehubah>[ ][ ]= new <jenis data> [baris][lajur]
Contoh :
int markah[ ][ ] = new int[4][3];
String nama[ ][ ] = new String[3][2];
Contoh aturcara :
import java.io.*;
class PelajarKelas
{
public static void main (String args[]) throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
int j;
String nama[ ][ ]=new String[3][2];
int r, c;
for (r=0; r<3; r++) /* Baris- kelas: for (r=0; r<=2; r++) */
{
System.out.println("Kelas = "+(r+1));
for (c=0; c<2; c++) /* Lajur- nama: for (c=0;c<=1; c++) */
{
System.out.print("Masukkan nama :");
nama[r][c] = stdin.readLine();
Muka Surat / Page : 6
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
}
}
for (r=0; r<3; r++) /* Baris- kelas: for (r=0; r<=2; r++) */
{
System.out.println("Kelas : "+(r+1));
for (c=0; c<2; c++) /* Lajur- nama:for (c=0;c<=1; c++) */
{
System.out.println("Nama : "+nama[r][c]);
} //end for
}
} //end of public static void main
} //end of class
Soalan Latihan
1) Isytiharkan tatasusunan satu dimensi dan beri nilai awal berat 5 orang pelajar (Berat :
45.5, 65.3, 65.6, 58.5, 80.6).
2) Isytiharkan tatasusunan satu dimensi dan beri nilai awal gred yang dicapai oleh 4 orang
pelajar bagi modul 1 (Gred : A, E, B, C).
3) Isytiharkan tatasusunan satu dimensi yang bersaiz 3 untuk menyimpan jumlah wang yang
dibelanjakan setiap hari.
4) Isytiharkan tatasusunan satu dimensi yang bersaiz 8 untuk menyimpan aksara yang
mewakili bangsa seseorang (contoh : M, C, I, L).
5) Isytiharkan tatasusunan dua dimensi dan beri nilai awal perbelanjaan harian 3 orang
selama 5 hari.
6) Isytiharkan tatasusunan dua dimensi yang terdiri dari 5 baris dan 4 lajur untuk
menyimpan jumlah wang yang dibelanjakan setiap hari.
Muka Surat / Page : 7
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
STRING DECLARATION
String merupakan satu urutan aksara.
Menggunakan kelas String, nilai awal bagi text boleh dibuat secara terus.
Contoh :
Kelas String boleh digunakan untuk manipulasi teks seperti membandingkan teks, mencantum
teks dan sebagainya.
Java menyediakan dua jenis kelas untuk manipulasi teks :
1. String class
2. StringBuffer class
class Msg
{
public static void main(String arg[])
{
String message = new String();
System.out.println(message);
}
}
class HelloString
{
public static void main(String arg[])
{
char hello[]= {'H','E', 'L', 'L', 'O'};
String message=new String(hello);
System.out.println(message); //print a String object name
}
}
3. To Create A String Object That Contains The Same Character Sequence As Another Object
e.g :
class HelloString
{
public static void main(String arg[])
{
char hello[]= {'H','E', 'L', 'L', 'O'};
String message=new String(hello);
String message2=new String(message); // Create A String Object
That Contains The Same Character Sequence as Another Object
System.out.println(“message 1”+message);
System.out.println(“message 2”+message2);
}
}
Muka Surat / Page : 8
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
e.g :
String hobi =”Membaca novel”;
System.out.println("Hobi - "+hobi);
STRING FUNCTIONS
class Lengthstr
{
public static void main(String args[])
{
String msg = “Please keep our room clean and tidy”;
int numchar = msg.length();
System.out.println(“Number of character = “+numchar);
}
}
0 1 2 3 4 index
e.g :
String testing = “THIS IS A TEST”;
int lastindex_s = testing.lastIndexOf(‘S’);
System.out.println(“Last Index of character S = “+lastindex_s);
e.g :
String msg = “Thif if a teft”; f – original
String msg2 = msg.replace(‘f’, ‘s’); s - replace
System.out.println(“Old String = “+msg);
System.out.println(“New String = “+msg2);
8. trim() – to trim the leading and trailing white spaces in a string - Trimchar
e.g:
String hello=” Hello Malaysia “;
String hello2=hello.trim();
System.out.println(“hello = “ +hello);
System.out.println(“hello2 = “ +hello2);
e.g:
String name=”MUHAMMAD”;
String name2=name. toLowerCase();
System.out.println(“name = “ +name);
System.out.println(“name2 = “ +name2);
e.g:
String name3="aminah";
String name4=name. toUpperCase();
System.out.println("\nnama = " +name3);
System.out.println("nama2 = " +name4);
0 1 2 3 4 5 6 7 8 9 10 11 12 13 INDEX
T H I S I S A T E S T
e.g:
Soalan Latihan :
Apakah kelas?
Kelas merupakan templat/blueprint yang digunakan untuk mencipta objek.
Kelas mewakili objek dan set operasi yang boleh diaplikasikan untuk objek tersebut.
Mencipta kelas :
Contoh 1:
Contoh 2:
public class Dog
{
String breed;
int ageC;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
Muka Surat / Page : 11
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
Constructor
Apabila membincangkan tentang kelas, salah satu topik sub yang paling penting ialah
constructor. Setiap kelas mempunyai constructor. Jika kita tidak menulis constructor untuk
kelas, pengkompil Java akan membina constructor lalai untuk kelas itu.
Definisi: Constructor merupakan satu method yang membolehkan objek memberi nilai awal
kepada dirinya sendiri semasa ia dicipta.
Contoh constructor:
Objek dicipta daripada kelas. Dalam java, kita menggunakan katakunci new untuk
mencipta objek.
Terdapat tiga langkah untuk mencipta objek daripada kelas:
Declaration : Pengisytiharan pembolehubah dengan nama dan jenis objek.
Instantiation : Katakunci new digunakan untuk mencipta objek’
Initialization : Katakunci new diikuti dengan panggilan kepada constructor.
Panggilan ini akan memberikan nilai awal kepada objek baru.
Contoh :
Output :
Contoh ini menerangkan bagaimana untuk mengakses instance variables dan method di
dalam kelas.
Muka Surat / Page : 13
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
OVERLOADING
Method Overloading is a feature that allows a class to have two or more methods having same
name, if their argument lists are different.
Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding
where binding of method call to its definition happens at Compile time.
As discussed above, method overloading can be done by having different argument list. Lets
see examples of each and every case.
When methods name are same but number of arguments are different.
class DisplayOverloading
{ public void disp(char c) {
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
Muka Surat / Page : 15
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10
In the above example – method disp() has been overloaded based on the number of arguments
– We have two definition of method disp(), one with one argument and another with two
arguments.
In this example, method disp() is overloaded based on the data type of arguments – Like
example 1 here also, we have two definition of method disp(), one with char argument and
another with int argument.
class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)
{
System.out.println(c );
}
}
Muka Surat / Page : 16
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
Output:
a
5
Here method disp() is overloaded based on sequence of data type of arguments – Both the
methods have different sequence of data type in argument list. First method is having argument
list as (char, int) and second is having (int, char). Since the sequence is different, the method
can be overloaded without any issues.
class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp"
);
}
}
class Sample3
{
Muka Surat / Page : 17
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
Case 1:
Case 2:
Case 3:
Case 4:
Case 5:
class Demo
{
public int myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample4
{
public static void main(String args[])
{
Demo obj1= new Demo();
obj1.myMethod(10,10);
obj1.myMethod(20,12);
}
}
Muka Surat / Page : 19
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
Answer:
It will throw a compilation error: More than one method with same name and argument list
cannot be defined in a same class.
Question 2 – return type is different. Method name & argument list same.
class Demo2
{
public double myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample5
{
public static void main(String args[])
{
Demo2 obj2= new Demo2();
obj2.myMethod(10,10);
obj2.myMethod(20,12);
}
}
Answer:
It will throw a compilation error: More than one method with same name and argument list
cannot be given in a class even though their return type is different. Method return type
doesn’t matter in case of overloading.
Declaring a method in subclass which is already present in parent class is known as method
overriding. Earlier we shared method overloading in java. In this tutorial we will see method
overriding with examples.
Example:
One of the simplest example – Here Boy class extends Human class. Both the classes have a
common method void eat(). Boy class is giving its own implementation to the eat() method or in
other words it is overriding the method eat().
Muka Surat / Page : 20
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
class Human{
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
obj.eat();
}
}
Output:
Boy is eating
The main advantage of method overriding is that the class can give its own specific
implementation to an inherited method without even modifying the parent class (base class).
Dynamic method dispatch is a technique which enables us to assign the base class reference
to a child class object. As you can see in the below example that the base class reference is
assigned to child class object.
class ABC{
public void disp()
{
System.out.println("disp() method of parent class");
}
public void abc()
{
System.out.println("abc() method of parent class");
}
}
class Test extends ABC{
public void disp(){
System.out.println("disp() method of Child class");
}
public void xyz(){
System.out.println("xyz() method of Child class");
}
Muka Surat / Page : 21
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
Note: In dynamic method dispatch the object can call the overriding methods of child class and
all the non-overridden methods of base class but it cannot call the methods which are newly
declared in the child class. In the above example the object obj was able to call
thedisp()(overriding method) and abc()(non-overridden method of base class). However if you
try to call the xyz() method (which has been newly declared in Test class) [obj.xyz()] then it
would give compilation error with the following message:
1. Argument list: The argument list of overriding method must be same as that of the
method in parent class. The data types of the arguments and their sequence should be
maintained as it is in the overriding method.
2. Access Modifier: The Access Modifier of the overriding method (method of subclass)
cannot be more restrictive than the overridden method of parent class. For e.g. if the
Access Modifier of base class method is public then the overriding method (child class
method ) cannot have private, protected and default Access modifier as all of the three
are more restrictive than public.
Muka Surat / Page : 22
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
For e.g. This is not allowed as child class disp method is more restrictive(protected) than
base class(public)
class MyBaseClass{
public void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends MyBaseClass{
protected void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Output:
class MyBaseClass{
protected void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends MyBaseClass{
public void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Output:
3. private, static and final methods cannot be overridden as they are local to the class.
However static methods can be re-declared in the sub class, in this case the sub-class
method would act differently and will have nothing to do with the same static method of
parent class.
Muka Surat / Page : 23
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
class ABC{
public void mymethod()
{
System.out.println("Class ABC: mymethod()");
}
}
class Test extends ABC{
public void mymethod(){
//This will call the mymethod() of parent class
super.mymethod();
System.out.println("Class Test: mymethod()");
}
public static void main( String args[]) {
Test obj = new Test();
obj.mymethod();
}
}
Output: