You are on page 1of 40

Kuliah 01 Pengenalan PBO Berbasis Java

IF307 PEMROGRAMAN BERORIENTASI OBJEK (JAVA)

NIKO IBRAHIM, MIT ERICK COSTANIO, S.KOM

FAKULTAS TEKNOLOGI INFORMASI UNIVERSITAS KRISTEN MARANATHA 2010

Class Attendance
Lectures schedule: Class A: Monday, 08.00 10.00 Class B: Monday, 10.30 13.00 Practical work schedule: Class A: Wednesday, 08.00 10.00 Class B: Wednesday, 10:00 12:00 All students must meet 75% of lectures attendances

to be eligible for the exams.

On Time
Students are expected to come on time for both

lectures and practicals sessions. More than 10 minutes means no proof of attendace

Books & References


You may use any books you like most
However, for your guidelines: Object of Java (BlueJ Edition) Core Java 2 Volume 1 Fundamental 8th Edition Other References Java 6 API Documentation (Java Doc) BlueJ Tutorials BlueJ Reference Manual

Practical Works
There are several practical works Checkpoint system (1-5 stage for each pracs)
Checkpoint 1 - basic concepts (everyone) Checkpoint 2 - understand and describe (nearly everyone) Checkpoint 3 - apply to new contexts (most) Checkpoint 4 - compare, synthesize (only top 40%) Checkpoint 5 - generalize, hypothesize, analyze (only top 20%) Try your best, do not copy others work

No late submission, no excuse


No cheating, no copying, no sharing

Work independently, ask for help

Softwares and Tools


JDK 1.6 + Java API Documentation
Editors: BlueJ (www.bluej.org): java editor + OOP concept JGrasp (www.jgrasp.org): Java editor NetBeans 6.9 (Java IDE) Others:
Text

Editor: Notepad, EditPlus, TextPad, UltraEdit, dll Java Editor: JCreator, DrJava IDE: Eclipse, IntelliJ IDEA

Silabus Perkuliahan
Pertemuan
Minggu 1 Minggu 2 Minggu 3 Minggu 4 Minggu 5 Minggu 6 Perkuliahan ditiadakan Pengenalan Pemrograman Berorientasi Objek (Java) Mengenal lebih dalam Java API dan Java Documentation Konsep Pemrograman Berorientasi Objek: Class, Object Method, Attributes, Encapsulation, & Overloading Libur Hari Raya Idul Fitri

Perkuliahan
Materi Tanggal 09 Agt 16 Agt 23 Agt 30 Agt 06 Sep 13 Sep

Praktikum
P1 Java Lang 1 P2 Java Lang 2 P3 Java Sun Rise P4 Smiley Face P5 Java Clock P6 Color Matcher

Minggu 7 Minggu 8 UTS Minggu 9 Minggu 10 Minggu 11 Minggu 12 Minggu 13 Minggu 14 Minggu 15 UAS

Konsep Inheritance, Overriding, & Polymorphism Review Materi Ujian Teori Abstract Class dan Interface OOP Advanced Features & Exception Handling Java Collections Framework Java Graphical User Interface (GUI) Bagian 1 Java Graphical User Interface (GUI) Bagian 2 Java Input/Output (Java IO) Review Materi Ujian Teori

20 Sep 27 Sep 4-6 Okt 18 Okt 25 Okt 01 Nov 08 Nov 15 Nov 22 Nov 29 Nov 6-18 Des

Ujian Praktikum P7 P8 P9 P10 P11 P12 Ujian Praktikum -

What Java?
1991: project Oak by James Gosling

Berorientasi objek, berdasarkan bahasa C++ Dirancang untuk memprogram home applicances seperti TV sets, freezers, dll Perlu berjalan di berbagai platform/processor dan harus murah

1994: HotJava (browser yang mampu menjalankan aplikasi java)

1995: implementasi publik yang pertama kali

Semua browsers dapat menjalankan aplikasi java di web (java applet)

1998: The advent of Java 2: J2EE, J2ME, & J2SE


2002: Microsoft memperkenalkan bahasa baru yang memiliki sintaks yang

mirip Java yaitu C# sebagai bagian dari platform .NET, sekaligus menghilangkan Java dari Windows (harus install manual) 2006: Sun released parts of Java as Free/Open Source Software! Versi saat ini: Java Development Kit (JDK) versi 1.6, biasa disebut JDK 6 In 2009, Sun Microsystem (the creator of Java) was acquired by Oracle (2nd largest software company in the world)

Why Java?
cheap almost all tools/softwares/components are available for

free! simple - partially modeled on C & C++ but greatly simplified and improved (eliminates pointers, simplifies multiple inheritance, etc.) object-oriented programming language

any conceptual component in your problem can be represented as an object in your program

portable Java programs are compiled (translated) into the Java Virtual Machine (JVM) code called bytecode bytecode is machine-independent and run on any machine with a Java interpreter the Java interpreter (part of JVM) further translates the bytecode into the machine language of the target machine once compiled programs can run on any platform (with JVM installed) without being recompiled

Why Java? (cont.)


robust (reliable) - well developed exception handling

mechanisms, early checking for errors, etc. secure - several built-in security mechanisms multithreaded - can perform several tasks simultaneously

Where Java?
Desktop applications
Web applications Ebay, Amazon, AirAsia, klikBCA Mobile Devices: mobile phone, smartphone, Blackberry,

PDA Smart Card: Simcard, Credit Card, RFID Card (Contoh: E-Tol) Enterprise Applications SAP, JD Edward, PeopleSoft, Oracle Business Suite All machines & OS: windows, linux, mac, solaris

Java Platform
http://download.oracle.com/javase/6/docs/

The following conceptual diagram illustrates all the

component technologies in Java SE platform and how they fit together.

Typical Java Development Environment


Ada 5 tahapan pengembangan aplikasi

menggunakan Java:

Tahap 1: Creating a program Tahap 2: Compiling the program into bytecodes Tahap 3: Loading the program into memory Tahap 4: Byte verification Tahap 5: Execution

Tahap 1: Creating a program


Pada tahap ini, kita membutuhkan suatu editor untuk

menulis kode program. Kode program disimpan pada file berekstensi .java Editor yang dapat digunakan:

Editor teks sederhana: notepad, editPlus, Textpad, UltraEdit Editor teks berbasis Java: JGrasp, JCreator, DoctorJava Editor teks + diagram sederhana: BlueJ Integrated Development Environment (IDE):
Free:

NetBeans, Eclipse, Oracle JDeveloper Commercial: IntelliJ IDEA, IBM, BEA, Borland JBuilder

Tahap 2: Compiling
Pada tahap ini, kita compile kode program menjadi bytecodes

dengan menggunakan perintah javac Contoh:


Kita membuat program dengan nama Welcome.java Perintah compile: javac Welcome.java Apabila proses compile berhasil, maka compiler akan menghasilkan sebuah file dengan ekstensi .class yaitu Welcome.class

File .class bukan bahasa mesin, melainkan merupakan

Bytecodes yang dapat dimengerti oleh Java Virtual Machine (JVM)


JVM inilah yang akan mengeksekusi bytecodes ke dalam bahasa mesin JVM inilah yang menyebabkan Java begitu powerful, secure, scalable dan multi-platform/portable Bytecode ini dapat dieksekusi di mesin/platform apapun asalkan telah diinstal JVM yang dapat mengerti versi Java tempat bytecode tersebut dicompile sebelumnya

Untuk menjalankan JVM dan mengeksekusi program, kita

gunakan perintah java

Misalnya: java Welcome

Tahap 3-5
Phase 3: Loading a Program into Memory

In Phase 3, the program must be placed in memory before it can execute a process known as loading. The class loader takes the .class files containing the program's bytecodes and transfers them to primary memory. The class loader also loads any of the .class files provided by Java that our program uses.

Phase 4: Bytecode Verification

In Phase 4, as the classes are loaded, the bytecode verifier examines their bytecodes to ensure that they are valid and do not violate Java's security restrictions. In Phase 5, the JVM executes the program's bytecodes, thus performing the actions specified by the program.

Phase 5: Execution

Latihan 1: HelloMe.java
Berdasarkan program HelloWorld.java, buatlah

sebuah program baru bernama HelloMe.java Pada saat di-run, program harus menampilkan pesan sbb: Hello World, Niko! Note:

Ganti dengan nama Anda sendiri Biasakan beri NRP dan Nama anda (dalam bentuk comment)

Pertanyaan: apa perbedaan antara print dan

println ?

Pembahasan Program
0: // Exercise 1: HelloMe.java 1: // NIK: 730015, NAMA: Niko Ibrahim 2: public class HelloMe { 3: public static void main (String args[ ]) { 4: System.out.println("Hello World, Niko!"); 5: } 6: } Line 0: Komentar program, judul program, keterangan penting. Line 1: Selalu tuliskan identitas penulis program. Line 2: - Nama kelas. Setiap program Java minimal memiliki 1 deklarasi kelas. - Kelas diawali huruf kapital untuk setiap kata. - Untuk men-save public class ke file, harus diberi nama sesuai dengan nama kelas tsb dan diakhiri dengan ekstensi .java. Tentang public akan dibahas nanti. Line 3: main method the starting point of every Java application Line 4: instruksi pada komputer untuk menulis suatu String (kata-kata)

Compile & Run menggunakan command window


Kita dapat menggunakan command window

untuk melakukan compile dan run program Java. Jalankan command window:

Start menu run ketik cmd Masuk ke direktori tempat Anda menyimpan file HelloMe.java

PERINTAH COMPILE
PERINTAH RUN

: javac HelloMe.java : java HelloMe

Note: JAVA PATH harus di-set terlebih dahulu di sistem operasi

print, println,dan printf


Untuk menuliskan sesuatu, Java memberikan 3

pilihan methods:

print posisi akhir kursor berada di garis yang sama


Contoh:

System.out.print ("Hello World");

println posisi akhir kursor berada di garis yang baru (seolah menekan enter)
Contoh:

System.out.println("Hello World");

printf print dalam bentuk format tertentu (f = formatted)


Contoh:

System.out.printf("%s\n %s\n", "Hello", "World");

Karakter Khusus
Kita juga dapat memasukan karakter khusus ke dalam String.

Sequence
\n \t \r \ \\

Character

New line Tab Return Quotation Mark Backslash

Untuk itu kita perlu menggunakan tanda escape, sbb: Contoh:

String
"Code: JSPS\nPrice: $50.25" "Niko\tIbrahim\r\Maranatha\tUniversity" "Type \"x\" to exit" "C:\\java\\files"

Result
Code: JSPS

Price: $50.25 Niko Ibrahim


Maranatha University Type "x" to exit C:\java\files

Tipe Data Primitif


Java memiliki 8 tipe data primitif
Type
byte short int long float double char boolean 8 16 32 64 32 64 16 8

Bits

Bytes
1 2 4 8 4 8 2 1

Minimum Range
-128 or -27 -32,768 or -215 -2,147,483,648 or -231 -263 -3.4E38 -1.7E308 n/a n/a

Maximum Range
127 or 27-1 32,767 or 215-1 2,147,483,647 or 231-1 263-1 3.4E38 1.7E308 n/a n/a

float 7 significant digits double 16 significant digits

Variabel & Assignment


Java merupakan bahasa pemrograman yang bersifat static,

artinya kita harus mendeklarasikan nama variabel sebelum meng-assign suatu nilai Sintaks: tipeData namaVariabel Contoh:

int counter; counter = 1;

Kita juga dapat secara langsung meng-assign suatu nilai kepada

variabel:

int counter = 1; boolean valid = false; char letter = A; char letter = 65; double distance = 3.65e+9;

Untuk menginisialisai suatu konstanta, kita gunakan keyword

final:

final int DAYS_IN_NOVEMBER = 30; final double SALEX_TAX = 0.75

String di Java
String dapat berisi huruf, angka, dan karakter khusus String bukan merupakan tipe data primitif melainkan

tipe data reference Untuk menyambung (concat) dua/lebih string, gunakan operator + Syntax:
String variableName = value;

Examples:
String String String String String String message1 = "Invalid data entry"; message2 = " "; message3 = null; firstName = "Niko"; lastName = "Ibrahim"; name = firstName + " " + lastName;

Operator Aritmatika
Program seringkali membutuhkan berbagai operasi

aritmatika. Java menyediakan berbagai operasi aritmatika untuk melakukan:


Penjumlahan, Pengurangan, Pembagian, Perkalian, Sisa Pembagian

Parentheses ( )
Kita dapat menggunakan tanda kurung dalam

melakukan operasi aritmatika. Contoh: a dikalikan dengan hasil penjumlahan antara b dengan c Yang manakah yang benar?
1)

2)
3)

a * b + c a * (b + c) (a * (b + c))

Note: operasi di dalam kurung akan diproses

pertama kali!

Precedence dari operator aritmatika


Berikut ini adalah urutan pengerjaan operasi aritmatika

(precedence)

Contoh urutan pengerjaan:

More: Operator Aritmatika


Secara keseluruhan Java memiliki 9 operator aritmatika:
Operator + Name Addition # Operands 2 Description Add two operands

*
/ %

Subtraction Multiplication
Division Modulus

2 2
2 2

Subtract the right operand from the left Multiplies the right operand and left operand
Divides the right operand into the left operand Returns the value that is left over after dividing the right operand into the left operand Adds 1 to the operand (x = x + 1)

++

Increment

-+

Decrement
Positive Sign

1
1

Subtracts 1 from the operand (x = x -1)


Promotes byte, short, and char types to the int type Changes a positive value to negative, and vice versa

Negative Sign

Contoh-contoh operasi aritmatika


Integer Arithmetic: Double Arithmetic:

int x = 14;
int y = 8; Operations Results

double a = 8.5;
double b = 3.4; Operations Results

int result1 = x + y;
int result2 = x y;

result1 = 22
result2 = 6

double result9 = a + b;
double result10 = a b;

result9 = 11.9
result10 = 5.1

int result3 = x * y;
int result4 = x / y;

result3 = 112
result4 = 1

double result11 = a * b;
double result12 = a / b;

result11 = 28.90
result12 = 2.5

int result5 = x % y;
int result6 = -y + x; int result7 = --y;

result5 = 6
result6 = 6 result7 = 7

double result13 = a % b; result13 = 1.7


double result14 = -a + b; result14 = -5.1 double result15 = --a; result15 = 7.5 result16 = 4.4

int result8 = ++x; result8 = 15, x = 15 double result16 = ++b; Character Arithmetic: char letter1 = C; char letter2 = ++letter1; // letter1 = C // letter2 = D

Unicode integer is 67 Unicode integer is 68

Shorcut Assignment Operators


Java memiliki 6 shortcut assignment operators:
Operator Name = Assignment += Addition Description Assigns a new value to the variable Adds the operand to the starting variable value of the variable and assigns the result to the variable Subtraction Subtracts the operand from the starting value of the variable and assigns the result to the variable Multiplication Multiplies the operand by the starting value of the variable and assigns the result to the variable Division Divides the operand by the starting value of the variable and assigns the result to the variable
Modulus Derives the value that is left over after dividing the right operand by the value in the variable, and then assigns this value to the variable

-=

*=

/= %=

Contoh shortcut assignment operator


count += 1; // count -= 1; // total += 100.0; // total -= 100.0; // price *= .8; sum += nextNumber;//

count is increased by 1 count is decreased by 1 total is increased by 100.0 total is decreased by 100.0 // price is multiplied by 0.8 sum is increased by the value of nextNumber

Using Console for Input & Output


Mulai Java versi 5, cara paling mudah untuk mendapatkan input dari

console adalah dengan menggunakan Scanner class Untuk menampilkan output ke console adalah menggunakan method (fungsi) System.out.println Sebelum menggunakan Scanner class, kita harus melakukan proses import sbb:

import java.util.Scanner;
Untuk membaca input dari console, kita buat objek scanner dengan cara

menuliskannya sbb:

Scanner sc = new Scanner(System.in);


Ada 4 buah methods dari objek Scanner (yaitu sc) yang dapat kita gunakan

sesuai kebutuhan:
Method next() or nextLine() nextInt() nextDouble() nextBoolean() Description Reads a String value from the user Reads an integer value from the user Reads a double value from the user Reads a boolean value from the user

Latihan 2: Operasi Penambahan Integer


// Addition program that displays the sum of two numbers. import java.util.Scanner; // program uses class Scanner

public class Addition { // main method begins execution of Java application public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in );
int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user

sum = number1 + number2; // add numbers


System.out.print( "Sum is " + sum ); // display sum

} // end method main


} // end class Addition

Variabel dan Konsep Memori


Nama variable seperti number1, number2, dan sum

sebenarnya berkorenpondensi dengan lokasi di memori komputer. Setiap variabel memiliki nama, tipe, ukuran, dan nilai Kode dari contoh 2:
number1 = input.nextInt(); // read first number from user

Pada saat kode tsb dieksekusi, nomor yang diketik oleh user akan disimpan ke suatu lokasi dimemori yang telah diberikan kepada number1 oleh compiler. Misal, user memasukkan angka 45, maka komputer akan menyimpan nilai integer ke lokasi number1 sbb:

Variabel dan Konsep Memori (cont.)


number2 = input.nextInt(); // read second number from user

Memory locations after storing values for number1 and number2.

sum = number1 + number2; // add numbers

Memory locations after calculating and storing the sum of number1 and number2.

Latihan 3: InvoiceApp.java
// Latihan 3: InvoiceApp.java import java.util.Scanner; public class InvoiceApp { public static void main (String args[]) { // create a Scanner object Scanner sc = new Scanner(System.in); // read a string System.out.print("Enter product code: "); String productCode = sc.next(); // read a double value System.out.print("Enter price: "); double price = sc.nextDouble(); // read an int value System.out.print("Enter quantity: "); int quantity = sc.nextInt(); // perform a calculation and display the result double total = price * quantity; System.out.println(); System.out.println(quantity + " " + productCode + " @ " + price + " = " + total); } }

Ekspresi Boolean
Ekpresi Boolean biasanya digunakan untuk mengatur control

statements. Ekpresi Boolean menghasilkan nilai true atau false. Ada 6 operator relational yang membandingkan operand bertipe data primitif dan menghasilkan nilai boolean. Dalam suatu ekpresi boolean, suatu operand dapat berupa literal, ekpresi aritmatika, maupun keyword true atau false.
Operator == != Equality Inequality Name Description Returns a true value if both operands are equals Returns a true value if the left and right operands are not equal

>
< >= <=

Greater Than

Returns a true value if the left operand is greater than the right operand Less Than Return a true value if the left operand is less than the right operand Greater Than Or Equal Returns a true value if the left operand is greater than or equal to the right operand Less Than or Equal Return a true value if the left operand is less than or equal to the right operand

Contoh ekpresi boolean


discountPercent == 2.3 letter == y isValid == false subtotal != 0 years > 0 i < months subtotal >= 500
quantity <= reorderPoint

// // // // // // //

equal to a numeric literal equal to a char literal equal to the false value not equal to a numeric literal greater than a numeric literal less than a variable greater than or equal to a numeric literal // less than or equal to a variable

Kita juga dapat menggabungkan beberapa nilai Boolean

dengan menggunakan operator AND dan OR:


Operator && || ^ ! Name

AND OR XOR NOT

Example a && b a || b a ^ b !a

Description

true if both a and b are true true if either a or b (or both) is true true if only a or b is true true if a is not true

String Comparison
Karena String adalah suatu objek, bukan tipe data primitif,

kita tidak dapat menggunakan operator relational untuk membandingkannya. Kita harus menggunakan method equals atau equalgnoreCase yang dimiliki oleh kelas String. Contoh:

firstName.equals("Niko"); // equal to a string literal firstName.equalsIgnoreCase("Niko"); // equal to a string literal firstName.equals(""); // equal to an empty string !lastName.equals("Ibrahim"); // not equal to a string literal !code.equalsIgnoreCase(productCode); // not equal to another string variable firstName == null // equal to a null value firstName != null // not equal to a null value

Java 6 only: firstName.isEmpty()

// check if firstName is an empty string

Next Week!
Struktur Control: Looping
For

Loop For Each Loop While Loop Do While Loop

Branching
If

Else Switch Case

Konsep Arrays

Java Documentation

You might also like