Upload
dmaz-hendratmo
View
105
Download
2
Embed Size (px)
DESCRIPTION
belajar java blue j
Citation preview
I F 3 0 7 P E M R O G R A M A N B E R O R I E N T A S I O B J E K ( J A V A )
N I K O I B R A H I M , M I T
E R I C K C O S T A N I O , S . K O M
F A K U L T A S T E K N O L O G I I N F O R M A S I
U N I V E R S I T A S K R I S T E N M A R A N A T H A
2 0 1 0
Kuliah 01Pengenalan PBO Berbasis Java
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
PertemuanPerkuliahan Praktikum
Materi Tanggal
Minggu 1 Perkuliahan ditiadakan 09 Agt -
Minggu 2 Pengenalan Pemrograman Berorientasi Objek (Java) 16 Agt P1 Java Lang 1
Minggu 3Mengenal lebih dalam Java API dan Java Documentation
23 AgtP2 Java Lang 2
Minggu 4Konsep Pemrograman Berorientasi Objek: Class, Object
30 AgtP3 Java Sun Rise
Minggu 5 Method, Attributes, Encapsulation, & Overloading 06 Sep P4 Smiley FaceMinggu 6 Libur Hari Raya Idul Fitri 13 Sep P5 Java Clock
Minggu 7 Konsep Inheritance, Overriding, & Polymorphism 20 Sep P6 Color Matcher
Minggu 8 Review Materi 27 Sep Ujian PraktikumUTS Ujian Teori 4-6 Okt -Minggu 9 Abstract Class dan Interface 18 Okt P7Minggu 10 OOP Advanced Features & Exception Handling 25 Okt P8Minggu 11 Java Collections Framework 01 Nov P9Minggu 12 Java Graphical User Interface (GUI) Bagian 1 08 Nov P10Minggu 13 Java Graphical User Interface (GUI) Bagian 2 15 Nov P11Minggu 14 Java Input/Output (Java IO) 22 Nov P12Minggu 15 Review Materi 29 Nov Ujian PraktikumUAS Ujian Teori 6-18 Des -
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, sekaligusmenghilangkan 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 handlingmechanisms, 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 Platformhttp://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 aplikasimenggunakan 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 untukmenulis 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 bytecodesdengan 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 merupakanBytecodes 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 tersebutdicompile sebelumnya
Untuk menjalankan JVM dan mengeksekusi program, kitagunakan 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.
Phase 5: Execution In Phase 5, the JVM executes the program's bytecodes, thus
performing the actions specified by the program.
Latihan 1: HelloMe.java
Berdasarkan program HelloWorld.java, buatlahsebuah program baru bernama HelloMe.java
Pada saat di-run, program harus menampilkanpesan sbb:
Hello World, Niko!
Note: Ganti dengan nama Anda sendiri
Biasakan beri NRP dan Nama anda (dalam bentukcomment)
Pertanyaan: apa perbedaan antara print danprintln ?
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 kelastsb 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 : javac HelloMe.java
PERINTAH RUN : java HelloMe
Note: JAVA PATH harus di-set terlebih dahulu disistem 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.
Untuk itu kita perlu menggunakan tanda escape, sbb: Contoh:
Sequence Character
\n New line\t Tab\r Return\ Quotation Mark\\ Backslash
String Result
"Code: JSPS\nPrice: $50.25" Code: JSPS
Price: $50.25"Niko\tIbrahim\r\Maranatha\tUniversity" Niko Ibrahim
Maranatha University"Type \"x\" to exit" Type "x" to exit
"C:\\java\\files" C:\java\files
Tipe Data Primitif
Java memiliki 8 tipe data primitifType Bits Bytes Minimum Range Maximum Range
byte 8 1 -128 or -27 127 or 27-1
short 16 2 -32,768 or -215 32,767 or 215-1
int 32 4 -2,147,483,648 or -231 2,147,483,647 or 231-1
long 64 8 -263 263-1
float 32 4 -3.4E38 3.4E38
double 64 8 -1.7E308 1.7E308
char 16 2 n/a n/a
boolean 8 1 n/a n/a
float 7 significant digitsdouble 16 significant digits
Variabel & Assignment
Java merupakan bahasa pemrograman yang bersifat static, artinya kita harus mendeklarasikan nama variabel sebelummeng-assign suatu nilai
Sintaks: tipeData namaVariabel Contoh:
int counter;
counter = 1;
Kita juga dapat secara langsung meng-assign suatu nilai kepadavariabel: 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 message1 = "Invalid data entry";
String message2 = " ";
String message3 = null;
String firstName = "Niko";
String lastName = "Ibrahim";
String name = firstName + " " + lastName;
Operator Aritmatika
Program seringkali membutuhkan berbagai operasiaritmatika. Java menyediakan berbagai operasiaritmatika untuk melakukan:
Penjumlahan, Pengurangan,
Pembagian, Perkalian,
Sisa Pembagian
Parentheses ( )
Kita dapat menggunakan tanda kurung dalammelakukan operasi aritmatika.
Contoh: a dikalikan dengan hasil penjumlahanantara b dengan c
Yang manakah yang benar?1) a * b + c
2) a * (b + c)
3) (a * (b + c))
Note: operasi di dalam kurung akan diprosespertama kali!
Precedence dari operator aritmatika
Berikut ini adalah urutan pengerjaan operasi aritmatika(precedence)
Contoh urutan pengerjaan:
More: Operator Aritmatika
Operator Name # Operands Description
+ Addition 2 Add two operands
- Subtraction 2 Subtract the right operand from the left
* Multiplication 2 Multiplies the right operand and left operand
/ Division 2 Divides the right operand into the left operand
% Modulus 2 Returns the value that is left over after dividing the right operand into the left operand
++ Increment 1 Adds 1 to the operand (x = x + 1)
-- Decrement 1 Subtracts 1 from the operand (x = x -1)
+ Positive Sign 1 Promotes byte, short, and char types to the int type
- Negative Sign 1 Changes a positive value to negative, and vice versa
Secara keseluruhan Java memiliki 9 operator aritmatika:
Contoh-contoh operasi aritmatika
Integer Arithmetic:
int x = 14;
int y = 8;
Double Arithmetic:
double a = 8.5;
double b = 3.4;Operations Results Operations Results
int result1 = x + y;
int result2 = x y;
int result3 = x * y;
int result4 = x / y;
int result5 = x % y;
int result6 = -y + x;
int result7 = --y;
int result8 = ++x;
result1 = 22
result2 = 6
result3 = 112
result4 = 1
result5 = 6
result6 = 6
result7 = 7
result8 = 15, x = 15
double result9 = a + b;
double result10 = a b;
double result11 = a * b;
double result12 = a / b;
double result13 = a % b;
double result14 = -a + b;
double result15 = --a;
double result16 = ++b;
result9 = 11.9
result10 = 5.1
result11 = 28.90
result12 = 2.5
result13 = 1.7
result14 = -5.1
result15 = 7.5
result16 = 4.4Character Arithmetic:
char letter1 = C; // letter1 = C Unicode integer is 67
char letter2 = ++letter1; // letter2 = D Unicode integer is 68
Shorcut Assignment Operators
Java memiliki 6 shortcut assignment operators:Operator Name Description
= Assignment Assigns a new value to the variable
+= Addition 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 is increased by 1
count -= 1; // count is decreased by 1
total += 100.0; // total is increased by 100.0
total -= 100.0; // total is decreased by 100.0
price *= .8; // price is multiplied by 0.8
sum += nextNumber;// sum is increased by the
value of nextNumber
Using Console for Input & Output
Mulai Java versi 5, cara paling mudah untuk mendapatkan input dariconsole 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 caramenuliskannya sbb:
Scanner sc = new Scanner(System.in);
Ada 4 buah methods dari objek Scanner (yaitu sc) yang dapat kita gunakansesuai kebutuhan:
Method Description
next() or nextLine() Reads a String value from the user
nextInt() Reads an integer value from the user
nextDouble() Reads a double value from the user
nextBoolean() 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 applicationpublic static void main( String args[] ){
// create Scanner to obtain input from command windowScanner input = new Scanner( System.in );
int number1; // first number to addint number2; // second number to addint 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 dimemori 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 akandisimpan ke suatu lokasi dimemori yang telah diberikan kepadanumber1 oleh compiler.
Misal, user memasukkan angka 45, maka komputer akanmenyimpan 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 Name Description
== Equality Returns a true value if both operands are equals
!= Inequality 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 rightoperand
< Less Than Return a true value if the left operand is less than the rightoperand
>= Greater Than Or Equal Returns a true value if the left operand is greater than or equalto the right operand
Contoh ekpresi boolean
discountPercent == 2.3 // equal to a numeric literal
letter == y // equal to a char literal
isValid == false // equal to the false value
subtotal != 0 // not equal to a numeric literal
years > 0 // greater than a numeric literal
i < months // less than a variable
subtotal >= 500 // greater than or equal
to a numeric literal
quantity
String Comparison
Karena String adalah suatu objek, bukan tipe data primitif, kita tidak dapat menggunakan operator relational untukmembandingkannya.
Kita harus menggunakan method equals atauequalgnoreCase 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