Anda di halaman 1dari 58

HALTEGH

IT LEARNING CENTER

Java Array
Overview
HALTEGH
IT LEARNING CENTER

Java Array
● Array adalah suatu koleksi , mirip dengan elemen yang memiliki memeori yang
terus bertambah.
● Java array adalah objek yang berisikan elemen data yang sama semua tipenya .
Nilai datanya diset atau ditentukan secara manual oleh kita
● Array dijava disusun berdasarkan antrian yang disebut dengan index
HALTEGH
IT LEARNING CENTER

Keuntungan Java Array


● Code Optimization: Kita bias mengambil banyak data secara acak
atau sorting data/ mengurutkan data
● Random access: Kita dapat mendapatkan beberapa data berdasakan
indeksnya di lokasi manapun
HALTEGH
IT LEARNING CENTER

Kekurangan Java Array


● Size Limit: Kita menset nilainya secara menual atau fix
HALTEGH
IT LEARNING CENTER

Tipe Array di java

● Single Dimensional Array


● Multidimensional Array
HALTEGH
IT LEARNING CENTER

Syntax untuk mendeklarasikan Array


● dataType[] arr; (or)
● dataType []arr; (or)
● dataType arr[];
HALTEGH
IT LEARNING CENTER

Penyingkatan penulisan Array


● arrayRefVar=new datatype[size];
Contoh single dimensional java array
● Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Declaration, Instantiation and Initialization dari
Java Array
● Kita bias melakukanya secra bersamaan, yakni int a[] = {};
int a[]={33,3,4,5};//declaration, instantiation and initialization

● Here’s the example


class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Passing nilai Array ke method di java
● Nilai pada variable array dapat di passing atau di oper smaa seperti pada variable biasa, hanya saja
membutuhkan iterasi atau loop
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}}
Multidimensional Array
In such case, data is stored in row and column based index (also known as matrix
form).
Syntax untuk deklarasi Multidimensional Array di java
1.dataType[][] arrayRefVar; (or)
2.dataType [][]arrayRefVar; (or)
3.dataType arrayRefVar[][]; (or)
4.dataType []arrayRefVar[];

Contoh pembuatan Multidimensional Array di java


int[][] arr=new int[3][3];//
3 row and 3 column
Contoh inisialisasi Multidimensional Array di java
1.arr[0][0]=1;
2.arr[0][1]=2;
3.arr[0][2]=3;
4.arr[1][0]=4;
5.arr[1][1]=5;
6.arr[1][2]=6;
7.arr[2][0]=7;
8.arr[2][1]=8;
9.arr[2][2]=9;
Contoh Multidimensional java array
● Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
class Testarray3{
public static void main(String args[]){

//declaring and initializing 2D array


int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}

}}
What is the class name of java array?
In java, array is an object. For array object, an proxy class is created whose
name can be obtained by getClass().getName() method on the object.

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

int arr[]={4,4,5};

Class c=arr.getClass();
String name=c.getName();

System.out.println(name);

}}
Copying a java array
● We can copy an array to another by the arraycopy method of System class.

Syntax of arraycopy method


public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int
length
)
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);


System.out.println(new String(copyTo));
}
}
Penjumlahan Array 2 matric di java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Your Assignment
● What is the output of the program ? Explain it briefly.
class array_output
{
public static void main(String args[])
{
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i)
{
array_variable[i] = i;
System.out.print(array_variable[i] + "
");
i++;
}
}
}
Your Assignment
● What is the output of the program ? Explain it briefly.

class evaluate
{
public static void main(String args[])
{
int arr[] = new int[] {0 , 1, 2, 3, 4, 5,
6,7, 8, 9};
int n = 6;
n = arr[arr[n] / 2];
System.out.println(arr[n] / 2);
}
}
What is the output?
class multidimention_array
{
public static void main(String args[])
{
int arr[][] = new int[3][];
arr[0] = new int[1];
arr[1] = new int[2];
arr[2] = new int[3];
int sum = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < i + 1; ++j)
arr[i][j] = j + 1;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < i + 1; ++j)
sum + = arr[i][j];
System.out.print(sum);
}
HALTEGH
IT LEARNING CENTER

Java Interface
Java Interface
● An interface in java adalah blueprint dari suatu kelas. Dapat
memiliki satic constant dan abstract method .
● Interface di java adalah a mechanism untuk mencapai abstraction.
Hanya boleh ada abstract methods in di interface bukan di body
method. Digunakan untuk mencapai abstraction dan multiple
inheritance di Java.
● Java Interface juga representasi IS-A suatu hubungan.
● Tidak bisa diinisiasi seperti kelas abstract.
Kenapa menggunakan Java interface?
There are mainly three reasons to use interface. They are given below.

● Digunakan untuk mencapai abstraction.


● Support fungsionalitas untuk multiple inheritance
● It can be used to achieve loose coupling.
Internal addition by compiler
● Interface field yakni public, static dan final by default, dan method
nya public dan abstract.
The java compiler adds public and abstract keywords before the interface method.
More, it adds public, static and final keywords before data members.
Hubungan antara kelas dan interface
● Jika kita mau menggunakan interface pada kelas, untuk
menghubungkannya digunakan keyword implements
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Java 8 Static Method in Interface
● Since Java 8, we can have static method in interface. Let's see an example:
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
● Since Java 8, we can have method body in interface. But we need to make it default method. L
● et's see an example:
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Abstract class in Java
● A class that is declared with abstract keyword, is known as abstract
class in java. It can have abstract and non-abstract methods (method
with body).
● Before learning java abstract class, let's understand the abstraction in
java first.
Perbedaan antara abstract
class dan interface
Perbedaan antara abstract class dan interface

● Abstract class dan interface keduanya digunakan untuk mencapai


abstraction dimana kita bisa mendeklarasi metode abstrak. Abstract
class dan interface tidak bisa seketika menjadi program yang utuh /
sempurna.
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%)


whereas interface achieves fully abstraction (100%).
Contoh abstract class dan interface di Java
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
//Creating interface that has 4 methods
interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}
//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
//
Creating subclass of abstract class, now we need to provide the implementation of rest of the meth
ods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
//Creating a test class that calls the methods of A interface
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d(); }}
HALTEGH
IT LEARNING CENTER

End
Penamaan di Java
Name Convention
class name should start with uppercase letter and be a noun e.g.
String, Color, Button, System, Thread etc.

interface name should start with uppercase letter and be an adjective e.g.
Runnable, Remote, ActionListener etc.

method name should start with lowercase letter and be a verb e.g.
actionPerformed(), main(), print(), println() etc.

variable name should start with lowercase letter e.g. firstName,


orderNumber etc.

package name should be in lowercase letter e.g. java, lang, sql, util etc.

constants name should be in uppercase letter. e.g. RED, YELLOW,


MAX_PRIORITY etc.
CamelCase di java naming conventions
● Java follows camelcase syntax for naming the class, interface,
method and variable.
● Jika Namanya lebih dari satukata, maka kata kedua harus huruf
kapital e.g. actionPerformed(), firstName, ActionEvent,
ActionListener etc.
Java Package
Java Package
● A java package adalah paket yang berisikan kelas, interface, sub
class dsb dalam satu tempat
● Package dibuat oleh user
● Ada beberapa package bawaan di java, seperti, lang, awt, javax,
swing, net, io, util, sql etc.
Keuntungan menggunakan Java Package
● Mengkategorikan resource lebih rapih
● Meneyediakan hak akses resouurce
● Menghapus eror jika ada nama yang sama
Contoh java package
● Untuk membuat package diperlukan keyword package diikuti
Namanya apa
• //save as Simple.java
• package mypack;
• public class Simple{
• public static void main(String args[]){
• System.out.println("Welcome to package");
• }
• }
How to access package from another
package?
• There are three ways to access the package from outside the package.

● import package.*;
● import package.classname;
● fully qualified name.
Cara mengakses package dari package lain

● import package.*;
● import package.classname;
● fully qualified name.
1) Using packagename.*
● If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.
● The import keyword is used to make the classes and interface of
another package accessible to the current package.
Example of package that import the
packagename.*
//save by A.java
package pack;
public class A{
public void msg()
{System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
2) Using packagename.classname
● If you import package.classname then only declared class of this
package will be accessible.
Example of package by import
package.classname
//save by A.java

package pack;
public class A{
public void msg()
{System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
3) Using fully qualified name
● If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. But you
need to use fully qualified name every time when you are accessing
the class or interface.
● It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
Example of package by import fully qualified
name
//save by A.java
package pack;
public class A{
public void msg()
{System.out.println("Hello");}
}

//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//
using fully qualified name
obj.msg();
}
}
If you import a package, subpackages
will not be imported.
● If you import a package, all the classes and interface of that package
will be imported excluding the classes and interfaces of the
subpackages. Hence, you need to import the subpackage as well.
Sequence of the program must be package
then import then class.
Subpackage in java
● Package inside the package is called the subpackage. It should be created to
categorize the package further.
● Let's take an example, Sun Microsystem has definded a package named java
that contains many classes like System, String, Reader, Writer, Socket etc.
These classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation, Socket and ServerSocket classes are for networking etc
and so on. So, Sun has subcategorized the java package into subpackages such
as lang, net, io etc. and put the Input/Output related classes in io package,
Server and ServerSocket classes in net packages and so on.

The standard of defining package is domain.company.package e.g. com.java.bean


or org.sssit.dao.
Example of Subpackage
• package com.myjava.core;
• class Simple{
• public static void main(String args[]){
• System.out.println("Hello subpackage");
• }
•}
How to send the class file to another directory
or drive?
● There is a scenario, I want to put the class file of A.java source file
in classes folder of c: drive. For example:
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
HALTEGH
IT LEARNING CENTER

End

Anda mungkin juga menyukai