Difference between revisions of "Java: Intro Pemrogramman Java"

From OnnoWiki
Jump to navigation Jump to search
 
(24 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
Sumber: http://www.vogella.de/articles/JavaIntroduction/article.html
 +
 
* Tutorial ini menjelaskan tentang bahasa pemrogramman Java. Juga berisi "Contekan" dengan contoh untuk task standard saat pemrogramman.
 
* Tutorial ini menjelaskan tentang bahasa pemrogramman Java. Juga berisi "Contekan" dengan contoh untuk task standard saat pemrogramman.
 
* Tulisan ini tidak membahas tentang instalasi [[Java Development Kit]] ([[JDK]]).
 
* Tulisan ini tidak membahas tentang instalasi [[Java Development Kit]] ([[JDK]]).
Line 140: Line 142:
 
Untuk pendahuluan cara penggunakan Eclipse IDE mohon membaca-baca [[Eclipse: Tutorial Penggunaan | Eclipse Tutorial]] .
 
Untuk pendahuluan cara penggunakan Eclipse IDE mohon membaca-baca [[Eclipse: Tutorial Penggunaan | Eclipse Tutorial]] .
  
In the following I will say "Create
+
Selanjutnya akan di asumsikan bahwa proses pendefinisian variabel, konversi objek dll akan mengasumsikan penggunaan Eclipse IDE.
e.g. the types of the used variables must be pre-defined and conversion to other objects is relatively strict, e.g. must be done in most cases by the programmer. a Java project SomeName". This will refer to creating an Eclipse Java project. If you are using a different IDE please follow the required steps in this IDE.
 
  
 
===Aplikasi Graphical User Internet (GUI) yang Pertama===
 
===Aplikasi Graphical User Internet (GUI) yang Pertama===
  
Using Eclipse create a new Java project "JavaIntroductionUI".
+
Gunakan Eclipse buat project Java baru melalui perintah File -> New -> Java Project -> "JavaIntroductionUI" -> Finish.
  
Create the following class MyFirstUI.java in package ui.
+
Buat class melalui perintah Project JavaIntroductionUI -> src -> New -> Class -> package ui; MyFirstUI.java; public static void main(String[] args) -> Finish.
  
 
 
  package ui;
 
  package ui;
 
   
 
   
Line 155: Line 155:
 
  import java.awt.GridLayout;
 
  import java.awt.GridLayout;
  
e.g. the types of the used variables must be pre-defined and conversion to other objects is relatively strict, e.g. must be done in most cases by the programmer.
+
Tipe dari variable yang digunakan harus di definisikan di awal. Konversi ke objek lain umumnya sangat ketat, dan harus dilakukan umumnya oleh progreammer.
  
 
  import java.awt.event.ActionEvent;
 
  import java.awt.event.ActionEvent;
Line 224: Line 224:
 
   
 
   
 
  // Set a tooltip for the button
 
  // Set a tooltip for the button
  sayHello
+
  // sayHello
  setToolTipText("This button will say something really nice of something bad");
+
  // setToolTipText("This button will say something really nice of something bad");
 
  // sayHello need to do something
 
  // sayHello need to do something
 
  sayHello.addActionListener(new MyActionListener());
 
  sayHello.addActionListener(new MyActionListener());
Line 245: Line 245:
  
  
Create also the following class MainTester.java in package test and start this class.
+
Buat juga class MainTester.java di package test dan start class tersebut.
  
 
 
  package test;
 
  package test;
 
   
 
   
Line 259: Line 258:
 
  }
 
  }
  
+
Kita harusnya akan melihat tampilan berikut. Sebuah message dialog akan terlihat jika kita menekan tombol.
 +
 
 +
 
 +
==Statement / Pernyataan==
  
You should see the following. A mesage dialog should be seen if you press the button.
+
Berikut ini di jelaskan beberapa aspek dari software
  
6. Statements
+
===Operasi Boolean===
  
The following describes certain aspects of the software.
+
Gunakan == untuk membandingkan dua (2) primitif atau untuk melihat dua (2) referensi yang mengacu kepada objek yang sama. Gunakan method equals()  untuk melihat apakah dua (2) objek yang berbeda tersebut adalah sama.
  
6.1. Boolean Operations
+
&& dan || keduanya adalah Short Circuit Method artinya dia akan berhenti jika hasil evaluasi-nya jelas. Contoh (true || .... ) selalu benar (true_ sedang (false && ...) selalu salah (false). Contoh penggunaan:
  
Use == to compare two primitives or to see if two references refers to the same object. Use the equals() method to see if two different objects are equal.
+
(var !=null && var.method1()..)
  
&& and || are both Short Circuit Methods which means that they terminate once the result of an evaluation is already clear. Example (true || .... ) is always true while (false && ...) always false is. Usage:
+
Pastikan var tidak null sebelum melakukan test / check.
  
(var !=null && var.method1()..) ensures that var is not null before doing the real check.
 
  
 
Table 1. Boolean
 
Table 1. Boolean
Operations Description
+
{| border="1" cellpadding=2 style="border-collapse: collapse"
== Is equal, in case of objects the system checks if the reference variable point to the same object, is will not compare the content of the objects!
+
! Operasi
&& And
+
! Keterangan
!= is not equal, similar to the "=="
+
|-
a.equals(b) Checks if string a equals b
+
| ==
a.equalsIgnoreCase(b) Checks if string a equals b while ignoring lower cases
+
| sama dengan, jika Is equal, in case of objects the system checks if the reference variable point to the same object, is will not compare the content of the objects!
If (value ? false : true) {} Return true if value is not true. Negotiation
+
|-
 
+
| &&
6.2. Switch Statement
+
| And
 +
|-
 +
| !=
 +
| tidak sama dengan, mirip dengan "=="
 +
|-
 +
| a.equals(b)
 +
| Check string a sama dengan b
 +
|-
 +
| a.equalsIgnoreCase(b)
 +
| Check jika string a sama dengan b dan abaikan huruf kecil
 +
|-
 +
| If (value ? false : true) {}
 +
| Return true jika value tidak true. Negotiation
 +
|}
  
The switch statement can be used to handle several alternatives if they are based on the same constant value.
+
===Switch Statement===
  
 +
Statement switch dapat digunakan untuk menangani beberapa alternatif jika mereka berbasis pada nilai kontan yang sama
 
 
 
  switch (expression) {  
 
  switch (expression) {  
 
  case constant1:  
 
  case constant1:  
 
  command;  
 
  command;  
  break; // Will prevent that the other cases or also executed
+
  break; // Break sehingga case tidak di lanjutkan
 
  case constant2:
 
  case constant2:
 
  command;  
 
  command;  
Line 300: Line 315:
 
  }  
 
  }  
  
Example:
+
Contoh:
  
 
  switch (cat.getLevel()) {
 
  switch (cat.getLevel()) {
Line 318: Line 333:
 
 
  
7. Working with Strings
+
==Bekerja dengan String==
  
The following lists the most common string operations.
+
Daftar berikut berisi operasi string yang sering digunakan
  
Table 2.
 
Command Description
 
text1.equals("Testing"); return true if text1 is equal to "Testing". The test is case sensitive.
 
text1.equalsIgnoreCase("Testing"); return true if text1 is equal to "Testing". The test is not case sensitive. For example it would also be true for "testing"
 
StringBuffer str1 = new StringBuffer(); Define a new String with a variable length.
 
str.charat(1); Return the character at position 1. (Strings starting with 0)
 
str.substring(1); Removes the first characters.
 
str.substring(1, 5); Gets the substring from the second to the fifths character.
 
str.indexOf(String) Find / Search for String Returns the index of the first occurrence of the specified string.
 
str.lastIndexOf(String) Returns the index of the last occurrence of the specified string. StringBuffer does not support this method. Hence first convert the StringBuffer to String via method toString.
 
str.endsWith(String) Returns true if str ends with String
 
str.startsWith(String) Returns true if str starts with String
 
str.trim() Removes spaces
 
str.replace(str1,str2) Replaces all occurrences of str1 by str2
 
str.concat(str1); Concatenates str1 at the end of str.
 
str.toLowerCase() str.toUpperCase() Converts string to lower- or uppercase
 
str1 + str2 Concatenate str1 and str2
 
String[] zeug = myString.split("-"); String[] zeug = myString.split("\\."); Spits myString at / into Strings. Attention: the split string is a regular expression, so if you using special characters which have a meaning in regular expressions you need to quote them. In the second example the . is used and must be quoted by two backslashes.
 
  
8. Collection
+
{| border="1" cellpadding=2 style="border-collapse: collapse"
 +
! Perintah
 +
! Keterangan
 +
|-
 +
| text1.equals("Testing");
 +
| return true if text1 is equal to "Testing". The test is case sensitive.
 +
|-
 +
| text1.equalsIgnoreCase("Testing");
 +
| return true if text1 is equal to "Testing". The test is not case sensitive. For example it would also be true for "testing"
 +
|-
 +
| StringBuffer str1 = new StringBuffer();
 +
| Define a new String with a variable length.
 +
|-
 +
| str.charat(1);
 +
| Return the character at position 1. (Strings starting with 0)
 +
|-
 +
| str.substring(1);
 +
| Removes the first characters.
 +
|-
 +
| str.substring(1, 5);
 +
| Gets the substring from the second to the fifths character.
 +
|-
 +
| str.indexOf(String)
 +
| Find / Search for String Returns the index of the first occurrence of the specified string.
 +
|-
 +
| str.lastIndexOf(String)
 +
| Returns the index of the last occurrence of the specified string. StringBuffer does not support this method. Hence first convert the StringBuffer to String via method toString.
 +
|-
 +
| str.endsWith(String)
 +
| Returns true if str ends with String
 +
|-
 +
| str.startsWith(String)
 +
| Returns true if str starts with String
 +
|-
 +
| str.trim()
 +
| Removes spaces
 +
|-
 +
| str.replace(str1,str2)
 +
| Replaces all occurrences of str1 by str2
 +
|-
 +
| str.concat(str1);
 +
| Concatenates str1 at the end of str.
 +
|-
 +
| str.toLowerCase() str.toUpperCase()
 +
| Converts string to lower- or uppercase
 +
|-
 +
| str1 + str2
 +
| Concatenate str1 and str2
 +
|-
 +
| String[] zeug = myString.split("-"); String[] zeug = myString.split("\\.");
 +
| Spits myString at / into Strings. Attention: the split string is a regular expression, so if you using special characters which have a meaning in regular expressions you need to quote them. In the second example the . is used and must be quoted by two backslashes.
 +
|}
  
A collection is a data structure which is used to contain and process sets of data. The data is encapsulated and the access to the data is only possible via predefined methods.
+
==Collection==
  
For example if your applications saves data in the object People you can store different People objects about people in a collection.
+
Sebuah collection adalah struktur data yang digunakan untuk menyimpan dan memproses sekumpulan data. Data di enkapsulasi dan akses ke data hanya mungkin melalui metoda yang didefinisikan sebelumnya.
 +
 
 +
Contoh, jika aplikasi kita menyimpan data dalam objek People maka kita dapat menyimpan objek People yang berbeda tentang people di sebuah collection.
  
 
Tip
 
Tip
While arrays are fixed sized, collections have a dynamic size, e.g. a collection can contain a flexible number of object.
 
  
When you need elements of various types or a dynamically changing number of them you use Java Collections.
+
Sebuah array biasanya mempunyai besaran yang tetap. Collection mempunyai besaran yang dinamik, tidak tetap.
 +
Artinya, sebuah collection dapat berisi jumlah objek yang flexible.
  
Typical collections are: stacks, queues, deques, lists and trees.
+
Jika kita membutuhkan elemen dengan berbagai tipe atau jumlah yang berubah-ubah maka kita dapat menggunakan collection di Java.
  
As of Java 5 collections should get parameterized with an object declaration to enable the compiler to check if objects which are added to the collection have the correct type.
+
Beberapa collection adalah: stacks, queues, deques, lists and trees.
  
 +
ke 5 java collection harus di parameterisasi dengan sebuah deklarasi objek agar memungkinkan bagi compiler untuk mencek apakah objek yang di tambahkan ke collection mempunyai tipe data yang benar.
 
 
 
  package collections;
 
  package collections;
Line 378: Line 429:
 
 
  
java.util.Collections is the basis class which provides you useful functionality.
+
java.util.Collections adalah class dasar yang dapat memberikan fungsi yang kita butuhkan.
  
Table 3. Sample Table
 
Collections.copy(list, list) Copy a collection to another
 
Collections.reverse(list) Reserve the order of the list
 
Collections.shuffle(list) Shuffles the list
 
Collections.sort(list) Sort the list
 
  
9. Type Conversion
+
{| border="1" cellpadding=2 style="border-collapse: collapse"
 +
! Perintah
 +
! Keterangan
 +
|-
 +
| Collections.copy(list, list)
 +
| Copy sebuah collection ke yang lain
 +
|-
 +
| Collections.reverse(list)
 +
| Reserve urutan list
 +
|-
 +
| Collections.shuffle(list)
 +
| Acak list
 +
|-
 +
| Collections.sort(list)
 +
| Sort list
 +
|}
  
If you use variables of different types Java requires for certain types an explicit conversion. The following gives examples for this conversion.
+
==Konversi Tipe==
9.1. Conversion to String
 
  
Use the following to convert from other types to Strings
+
Jika kita menggunakan variable dari tipe yang berbeda, Java membutuhkan konversi yang explisit untuk tipe tertentu. Berikut ini adalah beberapa contoh dari konversi tersebut.
  
 +
===Konversi ke String===
 +
 +
Contoh konversi ke string yang lain
 
 
  // Convert from int to String
+
  // Konversi dari int ke String
 
  String s1 = String.valueOf ( 10 ); // "10" String s2 =
 
  String s1 = String.valueOf ( 10 ); // "10" String s2 =
  // Convert from double to String
+
  // Konversi dari double ke String
 
  String.valueOf ( Math.PI ); // "3.141592653589793"
 
  String.valueOf ( Math.PI ); // "3.141592653589793"
  // Convert from boolean to String
+
  // Konversi dari boolean ke String
 
  String s3 = String.valueOf ( 1 < 2 ); // "true"  
 
  String s3 = String.valueOf ( 1 < 2 ); // "true"  
  // Convert from date to String
+
  // Konversi dari date ke String
 
  String s4 = String.valueOf ( new Date() ); // "Tue Jun 03 14:40:38 CEST 2003"
 
  String s4 = String.valueOf ( new Date() ); // "Tue Jun 03 14:40:38 CEST 2003"
 
 
 
+
===Konversi dari String ke Number===
9.2. Conversion from String to Number
 
 
 
 
 
  // Conversion from String to int
+
  // Konversi dari String ke int
 
  int i = Integer.parseInt(String);
 
  int i = Integer.parseInt(String);
  // Conversion from float to int
+
  // Konversi dari float ke int
 
  float f = Float.parseFloat(String);
 
  float f = Float.parseFloat(String);
  // Conversion from double to int
+
  // Konversi dari double ke int
 
  double d = Double.parseDouble(String);  
 
  double d = Double.parseDouble(String);  
 
 
 +
Konversi dari string ke number tidak tergantung pada Locale settings, hasilnya menggunakan notifikasi Inggris untuk nomor. Dalam notifikasi ini format number yang benar adalah "8.20". Number Jerman "8,20" akan menghasilkan error.
  
The conversion from string to number is independent from the Locale settings, e.g. it is always using the English notification for number. In this notification a correct number format is "8.20". The German number "8,20" would result in an error.
+
Untuk mengkonversikan dari number Jerman kita harus menggunakan class NumberFormat. Masalahnya jika nilai yang ingin di konversikan adalah 98.00 maka class NumberFormat akan menghasilkan tipe Long yang tidak bisa di jadikan Double. Oleh karenya kita harus mengkonversikan dengan cara yang agak rumit sebagai berikut
 
 
To convert from a German number you have to use the NumberFormat class. The challenges is that if the value is for example 98.00 then the NumberFormat class would create a Long which cannot be casted to Double. Hence the following complex conversion class.
 
 
 
 
 
 
  private Double convertStringToDouble(String s) {
 
  private Double convertStringToDouble(String s) {
Line 439: Line 498:
 
  return result;
 
  return result;
 
  }
 
  }
 
  
9.3. Double to int
+
===Double ke int===
  
 
  int i = (int) double;
 
  int i = (int) double;
  
9.4. SQL Date conversions
+
===Konversi SQL Date===
 
 
Use the following to convert a Date to a SQL date
 
  
 +
gunakan cara berikut untuk konversikan Date ke SQL date
 
 
 
  package test;
 
  package test;
Line 479: Line 536:
 
===What is a jar===
 
===What is a jar===
  
A JAR file is a Java Archive based on the pkzip file format. A jar files can contain java classes and other resources (icons, property files) and can be executable.
+
Sebuah file JAR adalah sebuah Java arsip yang berbasis pada format file pkzip. Sebuah file jar berisi java class dan sumber daya lainnya (icon, file property) dan dapat di execute.
  
JAR files are the deployment format for Java. You can distribute your program in a jar file or you can use exiting java code via jars by putting them into your classpath.
+
File JAR adalah deployment format untuk java. Kita dapat distribusikan program kita dalam file java atau kita dapat menggunakan source code java yang ada melalui jar dengan cara meletakannya di classpath.
  
 
===Executable jar===
 
===Executable jar===
  
An executable JAR means the end-user doesn't have to pull the class files out before running the program. This is done via a manifest.txt file which tells the JVM which class has the main() method. The content of the manifest.txt file:
+
Sebuah executable JAR berarti end user tidak harus pusing meletakan class file sebelum menjalankan program tersebut. Hal ini dapat dilakukan melalui file manifest.txt yang memberitahukan JVM class mana yang mempunyai main() method. Isi dari manifest.txt file:
  
 
  Manifest-Version: 1.0 Main-Class: MyApp Class-Path:
 
  Manifest-Version: 1.0 Main-Class: MyApp Class-Path:
Line 491: Line 548:
 
 
  
An empty line is required otherwise the jar won't be executable. Space after a new line is also required
+
Sebuah "Empty Line" perlu di tuliskan kalau tdiak maka jar tidak akan di execure. Spasi sesudah kalimat baru juga di perlukan.
  
To create one executable JAR file run on the command line
+
Untuk membuat sebuah file executable JAR jalankan perintah berikut di command line
  
 
  jar -cvmf mainfest.txt app1.jar *.class
 
  jar -cvmf mainfest.txt app1.jar *.class
 
  
 
==Cheat Sheets==
 
==Cheat Sheets==
  
The following can be used as a reference for certain task which you have to do.
+
Berikt adalah beberapa referensi yang dapat digunakan untuk melakukan beberapa tugas tertentu.
  
===Working with classes===
+
===Bekerja dengan class===
  
While programming Java you have to create several classes, methods, instance variables. The following uses the package test.
+
Pada saat kita melakukan programming Java kita harus membuat beberapa class, method dan variable. Contoh berikut menggunakan package test.
  
Table 4.
 
What to do How to do it
 
Create a new class called "MyNewClass".
 
  
 +
Membuat class baru dengan nama "MyNewClass"
 
 
 
  package test;
 
  package test;
Line 517: Line 571:
 
  }
 
  }
  
 
  
Create a new attribute (instance variable) "var1" in MyNewClass with type String
+
Membuat attribute baru (instance variable) "var1" di MyNewClass dengan tipe String
  
 
 
Line 530: Line 583:
 
 
  
Create a Constructor for "MyNewClass which has a String parameter and assigns the value of it to the "var1" instance variable.
+
Membuat sebuah Constructor untuk "MyNewClass" yang mempunyai sebuah String parameter dan memberikan isinya ke "var1" instance variable.
 
 
 
 
 
  package test;
 
  package test;
Line 546: Line 598:
 
 
  
Create a new method "doSomeThing" in class which do not return a value and has no parameters
+
Membuat sebuah method "doSomeThing" di class yang tidak mengeluarkan nilai return dan tidak mempunyai parameter
  
 
 
Line 566: Line 618:
 
 
  
Create a new method "doSomeThing2" in class which do not return a value and has two parameters, a int and a Person
+
Membuat sebuah method "doSomeThing2" di class yang tidak memberikan nilai return dan mempunyai dua parameter, a int dan person
 
 
 
 
 
  package test;
 
  package test;
Line 590: Line 641:
 
 
  
Create a new method "doSomeThing2" in class which do return an int value and has three parameters, two Strings and a Person
+
Mebuat sebuah method "doSomeThing2" di class yang memberikan nilai return sebuah int dengan tiga (3) parameter, dua String dan Person
 
 
 
 
 
  package test;
 
  package test;
Line 618: Line 668:
  
 
 
 
+
Membuat "MyOtherClass" dengan dua (2) variabel instance. Satu untuk menyimpan String, satu lagi untuk menyimpan Dig. Membuat fasilitas untuk memperoleh dan menset variable tersebut.
Create a class "MyOtherClass" with two instance variables. One will store a String, the other will store a Dog. Create getter and setter for these variables.
+
 
 
 
 
  package test;
 
  package test;
 
   
 
   
Line 633: Line 681:
 
   
 
   
 
  public void setMyvalue(String myvalue) {
 
  public void setMyvalue(String myvalue) {
this.myvalue = myvalue;
+
this.myvalue = myvalue;
 
  }
 
  }
 
   
 
   
Line 643: Line 691:
 
  this.dog = dog;
 
  this.dog = dog;
 
  }
 
  }
  }  
+
  }
 
 
 
 
 
  
11.2. Working with local variable
+
===Bekerja dengan local variable===
  
A local variable must always be declared in a method.
+
Sebuah variable local harus di deklarasikan di method.
  
Table 5.
+
{| border="1" cellpadding=2 style="border-collapse: collapse"
What to do How to do it
+
! Apa yang dilakukan
Declare a (local) variable of type string. String variable1;
+
! Cara melakukan
Declare a (local) variable of type string and assign "Test" to it. String variable2 = "Test";
+
|-
Declare a (local) variable of type Person Person person;
+
| Declare a (local) variable of type string.
Declare a (local) variable of type Person, create a new Object and assign the variable to this object. Person person = new Person();
+
| String variable1;
Declare a array of type String String array[];
+
|-
Declare a array of type Person and create an array for this variable which can hold 5 Persons. Person array[]= new Person[5];
+
| Declare a (local) variable of type string and assign "Test" to it.
Assign 5 to the int variable var1 (which was already declared); var1 = 5;
+
| String variable2 = "Test";
Assign the existing variable pers2 to the exiting variable pers1; pers1 = pers2;
+
|-
Declare a ArrayList variable which can hold objects of type Person ArrayList<Person> persons;
+
| Declare a (local) variable of type Person
Create a new ArrayList with objects of type Person and assign it to the existing variable persons persons = new ArrayList<Person>();
+
| Person person;
Declare a ArrayList variable which can hold objects of type Person and create a new Object for it. ArrayList<Person> persons = new ArrayList<Person>();
+
|-
 +
| Declare a (local) variable of type Person, create a new Object and assign the variable to this object.
 +
| Person person = new Person();
 +
|-
 +
| Declare a array of type String
 +
| String array[];
 +
|-
 +
| Declare a array of type Person and create an array for this variable which can hold 5 Persons.
 +
| Person array[]= new Person[5];
 +
|-
 +
| Assign 5 to the int variable var1 (which was already declared);
 +
| var1 = 5;
 +
|-
 +
| Assign the existing variable pers2 to the exiting variable pers1;
 +
| pers1 = pers2;
 +
|-
 +
| Declare a ArrayList variable which can hold objects of type Person
 +
| ArrayList<Person> persons;
 +
|-
 +
| Create a new ArrayList with objects of type Person and assign it to the existing variable persons
 +
| persons = new ArrayList<Person>();
 +
|-
 +
| Declare a ArrayList variable which can hold objects of type Person and create a new Object for it.
 +
| ArrayList<Person> persons = new ArrayList<Person>();
 +
|}
  
 
==Referensi==
 
==Referensi==
  
 
* http://www.vogella.de/articles/JavaIntroduction/article.html
 
* http://www.vogella.de/articles/JavaIntroduction/article.html
 +
* http://java.lyracc.com/belajar/java-untuk-pemula/eclipse-ide
  
 
==Pranala Menarik==
 
==Pranala Menarik==

Latest revision as of 08:43, 5 September 2011

Sumber: http://www.vogella.de/articles/JavaIntroduction/article.html

  • Tutorial ini menjelaskan tentang bahasa pemrogramman Java. Juga berisi "Contekan" dengan contoh untuk task standard saat pemrogramman.
  • Tulisan ini tidak membahas tentang instalasi Java Development Kit (JDK).


Pendahuluan

Sejarah

Bahasa Pemrograman Java pertama kali di buat oleh James Gosling dari Sun Microsystems tahun 1991. Versi Java pertama yang tersedia untuk publik adalah Java 1.0 yang di release tahun 1995. Setelah melalui beberapa revisi dan perbaikan bahasa dan library. Versi Java sekarang adalah 1.6 yang juga di kenal sebagai Java 6.0.

Dari bahasa pemrogramman Java berevolusi Java platform. Java platform memungkinkan sebuah code yang di tulis dalam bahasa lain yang bukan bahasa pemrogramman Java dan masih dapat jalan di Java virtual machine.


Gambaran Umum

Bahasa pemrogramman Java terdiri dari Java compiler, Java virtual machine, dan Java class libraries. Java virtual machine (JVM) adalah software di komputer yang akan menjalankan program seperti mesin sesungguhnya.

Java compiler akan menterjemahkan source code Java menjadi byte-code. Java virtual machine akan menginterpretasikan byte-code dan menjalankan program.

Java virtual machine di tulis spesifik untuk sistem operasi yang spesifik.

Java runtime environment (JRE) terdiri dari JVM dan Java class libraries.


Karakteristik Java

Target Java adalah membuat sebuah program sekali saja, dan dapat di jalankan di banyak sistem operasi.

Jaka mempunyai karakteristik berikut:

  • Platform independent: Program Java menggunakan Java virtual machine untuk abstraksi dan tidak mempunyai akses secara langsung ke sistem operasi. Hal ini menyebabkan program Java sangat portabel. Sebuah program Java yang memenuhi standard dan mengikuti aturan tertentu dapat di jalankan tanpa di modifikasi di beberapa platform sekaligus, seperti, Windows atau Linux.
  • Bahasa Pemrogramman Object-orientated: Kecuali untuk tipe data primitif. Semua elemen di Java adalah objek.
  • Bahasa Pemrogramman Strongly-typed: Java adalah strongly-typed, dimana type dari variable yang digunakan harus di definikan terlebih dulu dan konversi ke objek lain sangat ketat, dimana harus dilakukan pada umumnya oleh programmer.
  • Bahasa Interpreted dan compiled: Java source code di transfer ke byte-code yang tidak tergantung pada platform targer-nya. Byte-code akan di interpretasikan oleh Java Virtual machine (JVM). JVM mempunyai Hotspot-Compiler yang akan menterjemahkan byte-code ke native code.
  • Manajemen Memory Automatis: Java mengatur alokasi dan de-alokasi memory untuk membuat objek baru. Program tidak mempunyai akses langsung ke memory. Garbage collector akan mendelete secara automatis objek yang tidak ada pointer ke padanya.

Sintaks Java mirip dengan C++, Java case sensitif, artinya, variabel myValue dan myvalue akan dilihat sebagai variabel yang BERBEDA.

Development menggunakan Java

Programmer akan menulis source code Java menggunakan text editor yang mendukung text ASCII biasa. Biasanya programmer menggunakan IDE (integrated development environment) untuk melakukan pemrogramman. Sebuah IDE akan membantu programmer dalam berbagai tugas menulis source code, misalnya, dia akan memberikan auto-formatting dari source code, memberikan highlight pada keyword yang penting dll.

Pada suatu saat programmer (atau IDE) akan memanggil Java compiler (javac). Java compiler akan membuat platform independent code yang di sebut bytecode. byte-code tersebut akan di simpan di file ".class".

Bytecode dapat di jalankan oleh Java runtime environment. Java runtime environment (JRE) adalah sebuah program yang mengetahui bagaimana cara menjalankan bytecode di sistem operasi. JRE menterjemahkan bytecode menjadi native code dan mengekskusinya. Jadi native code untuk Linux akan berbeda dengann native code untuk Windows.

Secara default, compiler akan meletakan setiap file class di directory ytang sama dengan file source. Kita biasanya dapat menentukan directory yang beda dengan -d

Classpath

Classpath adalah sambungan antara Java compiler dan Java interpreter. Classpath mendefinisikan dimana compiler dan interpreter menjadi file .class untuk di load.

Classpath di Java mendefinisikan Java class yang mana yang tersedia untuk program Java kita. Contoh, jika kita untuk menggunakan external Java library kita harus menambahkan library tersebut ke classpath kita untuk dapat menggunakannya di program kita,


Program Java Yang Pertama

Menulis Source Code

Program Java berikut di kembangkan di Linux. Proses di sistem operasi lain harusnya tidak berbeda jauh jadi tidak akan di bicarakan disini. Pilih directory tempat kita menyimpan source code. Disini akan digunakan directory ~/java yang selanjutnya akan disebut sebagai "javadir". Sebaiknya kita buat dulu directory tersebut

mkdir ~/java

Buka text editor untuk mengedit text biasa. Kita dapat menggunakan vi, bagi yang terbiasa menggunakan GUI sangat di sarankan untuk mengggunakan gedit. Ketik

gedit ~/java/HelloWorld.java

Isi dengan program java berikut

// The smallest Java program possible
public class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Simpan source code tersebut di directory "javadir" dengan nama "HelloWorld.java". Perhatikan bahwa nama file Java source HARUS SAMA dengan nama class (dalam source code) di tambahkan akhiran .java. Dalam kasus kita filename harus HelloWorld.java karena class yang dibuat adalah HelloWorld.


Compile Source Code

Untuk mengcompile source code. Masuk ke shell dan tulis

cd ~/java
javac HelloWorld.java

Cek isi folder menggunakan perintah

ls ~/java

harusnya sekarang ada file "HelloWorld.class". Jika kita melihat file tersebut, berarti kita berhasil mengcompile source Java pertama kita menjadi byte-code.

Menjalankan Code

Untuk menjalankan / me-run code kita dapat melakukannya dari shell menggunakan perintah

cd ~/java
java HelloWorld

Harusnya akan keluar kata-kata "Hello World".

Menggunakan classpath

Kita dapat menggunakan classpath untuk menjalankan program dari directory / tempat lain. Misalnya kita masuk ke shell kemudian masuk ke sembarang directory kemudian ketik

java HelloWorld

Jika kita tidak di directory dimana class yang sudah di compile berada maka sistem akan mengeluarkan error misalnya,

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld
	at java.net.URLClassLoader$1.run(URLClassLoader.java:202) 
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: HelloWorld.  Program will exit.

Untuk memperbaiki ini kita dapat menulis di shell

java -classpath "mydirectory" HelloWorld

Ubah "mydirectory" dengan directory dimana terdapat HelloWorld.class. Dalam hal ini menjadi

java -classpath "/home/namauseranda/java" HelloWorld

Perhatikan harus lengkap /home/namauseranda/java tidak bisa menggunakan ~/java. Sekarang, harusnya kita dapat melihat keluaran "HelloWorld".

Integrated Development Environment

Pada bagian sebelumnya di terangkan bagaimana cara membuat dan mengcompile program java menggunakan command line. Java Integrated Development Environment (IDE) memberikan banyak kemudahan fungsi untuk membuat program java. Salah satu IDE yang sangat powerful adalah Eclipse.

Untuk pendahuluan cara penggunakan Eclipse IDE mohon membaca-baca Eclipse Tutorial .

Selanjutnya akan di asumsikan bahwa proses pendefinisian variabel, konversi objek dll akan mengasumsikan penggunaan Eclipse IDE.

Aplikasi Graphical User Internet (GUI) yang Pertama

Gunakan Eclipse buat project Java baru melalui perintah File -> New -> Java Project -> "JavaIntroductionUI" -> Finish.

Buat class melalui perintah Project JavaIntroductionUI -> src -> New -> Class -> package ui; MyFirstUI.java; public static void main(String[] args) -> Finish.

package ui;

import java.awt.BorderLayout;
import java.awt.GridLayout;

Tipe dari variable yang digunakan harus di definisikan di awal. Konversi ke objek lain umumnya sangat ketat, dan harus dilakukan umumnya oleh progreammer.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField; 

public class MyFirstUI extends JFrame {

	private JCheckBox checkbox; 
	private JTextField firstName;
	private JTextField lastName;

	public MyFirstUI() {

		// Lets make it look nice
		// This you can ignore / delete if you don't like it
		// try {
		// for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
		// if ("Nimbus".equals(info.getName())) {
		// UIManager.setLookAndFeel(info.getClassName());
		// break;
		// }
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }

		setTitle("My First UI");

		// We create a panel which will hold the UI components
		JPanel pane = new JPanel(new BorderLayout());
		// We always have two UI elements (columns) and we have three rows
		int numberOfRows = 3;
		int numberOfColumns = 2;
		pane.setLayout(new GridLayout(numberOfRows, numberOfColumns));

		// create and attach buttons
		// create a label and add it to the main window
		JLabel firstNamelabel = new JLabel(" Firstname: ");
		pane.add(firstNamelabel);
		firstName = new JTextField();
		pane.add(firstName);

		JLabel lastNamelabel = new JLabel(" Lastname: ");
		pane.add(lastNamelabel);
		lastName = new JTextField();
		pane.add(lastName);

		JButton sayHello = new JButton("Say something");
		pane.add(sayHello);

		checkbox = new JCheckBox("Nice");
		pane.add(checkbox);

		// Add the pane to the main window
		getContentPane().add(pane);

		// Pack will make the size of window fitting to the compoents
		// You could also use for example setSize(300, 400);
		pack();

		// Set a tooltip for the button
		// sayHello
		// setToolTipText("This button will say something really nice of something bad");
		// sayHello need to do something
		sayHello.addActionListener(new MyActionListener());
	}

	private class MyActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (!checkbox.isSelected()) {
				JOptionPane.showMessageDialog(null, "I don't like you, "
						+ firstName.getText() + " " + lastName.getText() + "!");
			} else {
				JOptionPane.showMessageDialog(null, "How are you, "
						+ firstName.getText() + " " + lastName.getText() + "?");
			}
		}

	}
} 


Buat juga class MainTester.java di package test dan start class tersebut.

package test;

import ui.MyFirstUI;

public class MainTester {
	public static void main(String[] args) {
		MyFirstUI view = new MyFirstUI();
		view.setVisible(true);
	}
}

Kita harusnya akan melihat tampilan berikut. Sebuah message dialog akan terlihat jika kita menekan tombol.


Statement / Pernyataan

Berikut ini di jelaskan beberapa aspek dari software

Operasi Boolean

Gunakan == untuk membandingkan dua (2) primitif atau untuk melihat dua (2) referensi yang mengacu kepada objek yang sama. Gunakan method equals() untuk melihat apakah dua (2) objek yang berbeda tersebut adalah sama.

&& dan || keduanya adalah Short Circuit Method artinya dia akan berhenti jika hasil evaluasi-nya jelas. Contoh (true || .... ) selalu benar (true_ sedang (false && ...) selalu salah (false). Contoh penggunaan:

(var !=null && var.method1()..)

Pastikan var tidak null sebelum melakukan test / check.


Table 1. Boolean

Operasi Keterangan
== sama dengan, jika Is equal, in case of objects the system checks if the reference variable point to the same object, is will not compare the content of the objects!
&& And
!= tidak sama dengan, mirip dengan "=="
a.equals(b) Check string a sama dengan b
a.equalsIgnoreCase(b) Check jika string a sama dengan b dan abaikan huruf kecil
If (value ? false : true) {} Return true jika value tidak true. Negotiation

Switch Statement

Statement switch dapat digunakan untuk menangani beberapa alternatif jika mereka berbasis pada nilai kontan yang sama

switch (expression) { 
	case constant1: 
		command; 
		break; // Break sehingga case tidak di lanjutkan
	case constant2:
		command; 
		break;
		... 
	default: 
} 

Contoh:

switch (cat.getLevel()) {
			case 0:
				return true;
			case 1:
				if (cat.getLevel() == 1) {
					if  (cat.getName().equalsIgnoreCase(req.getCategory())) {
						return true;
					}
				}
			case 2:
				if (cat.getName().equalsIgnoreCase(req.getSubCategory())) {
					return true;
				}
			}


Bekerja dengan String

Daftar berikut berisi operasi string yang sering digunakan


Perintah Keterangan
text1.equals("Testing"); return true if text1 is equal to "Testing". The test is case sensitive.
text1.equalsIgnoreCase("Testing"); return true if text1 is equal to "Testing". The test is not case sensitive. For example it would also be true for "testing"
StringBuffer str1 = new StringBuffer(); Define a new String with a variable length.
str.charat(1); Return the character at position 1. (Strings starting with 0)
str.substring(1); Removes the first characters.
str.substring(1, 5); Gets the substring from the second to the fifths character.
str.indexOf(String) Find / Search for String Returns the index of the first occurrence of the specified string.
str.lastIndexOf(String) Returns the index of the last occurrence of the specified string. StringBuffer does not support this method. Hence first convert the StringBuffer to String via method toString.
str.endsWith(String) Returns true if str ends with String
str.startsWith(String) Returns true if str starts with String
str.trim() Removes spaces
str.replace(str1,str2) Replaces all occurrences of str1 by str2
str.concat(str1); Concatenates str1 at the end of str.
str.toLowerCase() str.toUpperCase() Converts string to lower- or uppercase
str1 + str2 Concatenate str1 and str2
String[] zeug = myString.split("-"); String[] zeug = myString.split("\\."); Spits myString at / into Strings. Attention: the split string is a regular expression, so if you using special characters which have a meaning in regular expressions you need to quote them. In the second example the . is used and must be quoted by two backslashes.

Collection

Sebuah collection adalah struktur data yang digunakan untuk menyimpan dan memproses sekumpulan data. Data di enkapsulasi dan akses ke data hanya mungkin melalui metoda yang didefinisikan sebelumnya.

Contoh, jika aplikasi kita menyimpan data dalam objek People maka kita dapat menyimpan objek People yang berbeda tentang people di sebuah collection.

Tip

Sebuah array biasanya mempunyai besaran yang tetap. Collection mempunyai besaran yang dinamik, tidak tetap.
Artinya, sebuah collection dapat berisi jumlah objek yang flexible.

Jika kita membutuhkan elemen dengan berbagai tipe atau jumlah yang berubah-ubah maka kita dapat menggunakan collection di Java.

Beberapa collection adalah: stacks, queues, deques, lists and trees.

ke 5 java collection harus di parameterisasi dengan sebuah deklarasi objek agar memungkinkan bagi compiler untuk mencek apakah objek yang di tambahkan ke collection mempunyai tipe data yang benar.

package collections;

import java.util.ArrayList;

public class MyArrayList {

	public static void main(String[] args) {
		// Declare the ArrayList
		ArrayList<String> var = new ArrayList<String>();
		// Add a few Strings to it
		var.add("Lars");
		var.add("Jennifer");
		// Loop over it and print the result to the console
		for (String s : var) {
			System.out.println(s);
		}
	}
}


java.util.Collections adalah class dasar yang dapat memberikan fungsi yang kita butuhkan.


Perintah Keterangan
Collections.copy(list, list) Copy sebuah collection ke yang lain
Collections.reverse(list) Reserve urutan list
Collections.shuffle(list) Acak list
Collections.sort(list) Sort list

Konversi Tipe

Jika kita menggunakan variable dari tipe yang berbeda, Java membutuhkan konversi yang explisit untuk tipe tertentu. Berikut ini adalah beberapa contoh dari konversi tersebut.

Konversi ke String

Contoh konversi ke string yang lain

// Konversi dari int ke String
String s1 = String.valueOf ( 10 ); // "10" String s2 =
// Konversi dari double ke String
String.valueOf ( Math.PI ); // "3.141592653589793"
// Konversi dari boolean ke String
String s3 = String.valueOf ( 1 < 2 ); // "true" 
// Konversi dari date ke String
String s4 = String.valueOf ( new Date() ); // "Tue Jun 03 14:40:38 CEST 2003"

Konversi dari String ke Number

// Konversi dari String ke int
int i = Integer.parseInt(String);
// Konversi dari float ke int
float f = Float.parseFloat(String);
// Konversi dari double ke int
double d = Double.parseDouble(String); 

Konversi dari string ke number tidak tergantung pada Locale settings, hasilnya menggunakan notifikasi Inggris untuk nomor. Dalam notifikasi ini format number yang benar adalah "8.20". Number Jerman "8,20" akan menghasilkan error.

Untuk mengkonversikan dari number Jerman kita harus menggunakan class NumberFormat. Masalahnya jika nilai yang ingin di konversikan adalah 98.00 maka class NumberFormat akan menghasilkan tipe Long yang tidak bisa di jadikan Double. Oleh karenya kita harus mengkonversikan dengan cara yang agak rumit sebagai berikut

private Double convertStringToDouble(String s) {

		Locale l = new Locale("de", "DE");
		Locale.setDefault(l);
		NumberFormat nf = NumberFormat.getInstance();
		Double result = 0.0;
		try {
			if (Class.forName("java.lang.Long").isInstance(nf.parse(s))) {
				result = Double.parseDouble(String.valueOf(nf.parse(s)));
			} else {
				result = (Double) nf.parse(new String(s));
			}
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		return result;
	}

Double ke int

int i = (int) double;

Konversi SQL Date

gunakan cara berikut untuk konversikan Date ke SQL date

package test;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ConvertDateToSQLDate {

private void convertDateToSQL(){ 
	 SimpleDateFormat template = 
			new SimpleDateFormat("yyyy-MM-dd"); 
		  java.util.Date enddate = 
			new java.util.Date("10/31/99"); 
		  java.sql.Date sqlDate = 
			java.sql.Date.valueOf(
			                template.format(enddate)); 
	 
}
	public static void main(String[] args) {
		ConvertDateToSQLDate date = new ConvertDateToSQLDate();
		date.convertDateToSQL();
	}	 

}

JAR files - Java Archive

What is a jar

Sebuah file JAR adalah sebuah Java arsip yang berbasis pada format file pkzip. Sebuah file jar berisi java class dan sumber daya lainnya (icon, file property) dan dapat di execute.

File JAR adalah deployment format untuk java. Kita dapat distribusikan program kita dalam file java atau kita dapat menggunakan source code java yang ada melalui jar dengan cara meletakannya di classpath.

Executable jar

Sebuah executable JAR berarti end user tidak harus pusing meletakan class file sebelum menjalankan program tersebut. Hal ini dapat dilakukan melalui file manifest.txt yang memberitahukan JVM class mana yang mempunyai main() method. Isi dari manifest.txt file:

Manifest-Version: 1.0 Main-Class: MyApp Class-Path:

. lib/jcommon-1.0.6.jar lib/itext-1.4.6.jar "Empty Line"


Sebuah "Empty Line" perlu di tuliskan kalau tdiak maka jar tidak akan di execure. Spasi sesudah kalimat baru juga di perlukan.

Untuk membuat sebuah file executable JAR jalankan perintah berikut di command line

jar -cvmf mainfest.txt app1.jar *.class

Cheat Sheets

Berikt adalah beberapa referensi yang dapat digunakan untuk melakukan beberapa tugas tertentu.

Bekerja dengan class

Pada saat kita melakukan programming Java kita harus membuat beberapa class, method dan variable. Contoh berikut menggunakan package test.


Membuat class baru dengan nama "MyNewClass"

package test;

public class MyNewClass {

}


Membuat attribute baru (instance variable) "var1" di MyNewClass dengan tipe String


package test;

public class MyNewClass {
	private String var1;
}


Membuat sebuah Constructor untuk "MyNewClass" yang mempunyai sebuah String parameter dan memberikan isinya ke "var1" instance variable.

package test;

public class MyNewClass { 
	private String var1;

	public MyNewClass(String para1) { 
		var1 = para1;
		// or this.var1= para1; 
	}
}


Membuat sebuah method "doSomeThing" di class yang tidak mengeluarkan nilai return dan tidak mempunyai parameter


package test;

public class MyNewClass {
	private String var1;

	public MyNewClass(String para1) {
		var1 = para1;
		// or this.var1= para1;
	}

	public void doSomeThing() {

	}

} 


Membuat sebuah method "doSomeThing2" di class yang tidak memberikan nilai return dan mempunyai dua parameter, a int dan person

package test;

public class MyNewClass {
	private String var1;

	public MyNewClass(String para1) {
		var1 = para1;
		// or this.var1= para1;
	}

	public void doSomeThing() {

	}

	public void doSomeThing2(int a, Person person) {

	}

}


Mebuat sebuah method "doSomeThing2" di class yang memberikan nilai return sebuah int dengan tiga (3) parameter, dua String dan Person

package test;

public class MyNewClass {
	private String var1;

	public MyNewClass(String para1) {
		var1 = para1;
		// or this.var1= para1;
	}

	public void doSomeThing() {

	}

	public void doSomeThing2(int a, Person person) {

	}

	public int doSomeThing3(String a, String b, Person person) {
		return 5; // Any value will do for this example
	}

} 


Membuat "MyOtherClass" dengan dua (2) variabel instance. Satu untuk menyimpan String, satu lagi untuk menyimpan Dig. Membuat fasilitas untuk memperoleh dan menset variable tersebut.

package test;

public class MyOtherClass {
	String myvalue;
	Dog dog;

	public String getMyvalue() {
		return myvalue;
	}

	public void setMyvalue(String myvalue) {
		this.myvalue = myvalue;
	}

	public Dog getDog() {
		return dog;
	}

	public void setDog(Dog dog) {
		this.dog = dog;
	}
}

Bekerja dengan local variable

Sebuah variable local harus di deklarasikan di method.

Apa yang dilakukan Cara melakukan
Declare a (local) variable of type string. String variable1;
Declare a (local) variable of type string and assign "Test" to it. String variable2 = "Test";
Declare a (local) variable of type Person Person person;
Declare a (local) variable of type Person, create a new Object and assign the variable to this object. Person person = new Person();
Declare a array of type String String array[];
Declare a array of type Person and create an array for this variable which can hold 5 Persons. Person array[]= new Person[5];
Assign 5 to the int variable var1 (which was already declared); var1 = 5;
Assign the existing variable pers2 to the exiting variable pers1; pers1 = pers2;
Declare a ArrayList variable which can hold objects of type Person ArrayList<Person> persons;
Create a new ArrayList with objects of type Person and assign it to the existing variable persons persons = new ArrayList<Person>();
Declare a ArrayList variable which can hold objects of type Person and create a new Object for it. ArrayList<Person> persons = new ArrayList<Person>();

Referensi

Pranala Menarik