Vous êtes sur la page 1sur 17

1.

Program Sederhana
//helloworld.java public class HelloWorld { public static void main(String args[]){ System.out.println("Hello World!!"); } } /* Nama File : ArgumentInput.java */ /* Nama Kelas : ArgumentInput */ /* Pembuat : Hananto Widhi */ /* Deskripsi : Contoh pembacaan argumen program dalam bahasa java */ /* Run dengan mengetikkan misalnya: java ArgumentInput 1 2 aku coba */ public class ArgumenInput { public static void main(String args[]) { if (args.length==0) { System.out.println("type: java ArgumenInput arg0 arg1 argn"); }else { for (int i=0;i<args.length;i++) { System.out.println("argument "+i+" is :"+args[i]); } } } }

2. Input/Output
/* Nama File : InputOutput.java */ /* Nama Kelas : InputOutput */ /* Pembuat : Hananto Widhi */ /* Deskripsi : Implementasi membaca type dasar dalam bahasa JAVA */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Scanner; public class InputOutput { public static void main(String args[]) { /* kamus lokal */ int i = 0; float f = 0.0f; double d = 0.0; boolean b = false; String s = null; char c = ' ';

/* Prosedur baca dari standar input, berjalan di JAVA versi 1.0 keatas */ System.out.println("Contoh pembacaan dari standar input (berjalan di JAVA versi 1.0 keatas)"); BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("masukkan nilai int:");i=Integer.parseInt(is.readLine()); System.out.print("masukkan nilai float:");f=Float.parseFloat(is.readLine()); System.out.print("masukkan nilai double:");d=Double.parseDouble(is.readLine()); System.out.print("masukkan nilai boolean:");b=Boolean.parseBoolean(is.readLine()); System.out.print("masukkan nilai String:");s=is.readLine(); System.out.print("masukkan nilai character:");c=(char)is.read(); }catch(IOException e) { System.out.println(e); } /* Prosedur tulis ke standar output */ System.out.println("nilai int:"+i); System.out.println("nilai float:"+f); System.out.println("nilai double:"+d); System.out.println("nilai boolean:"+b); System.out.println("nilai String:"+s); System.out.println("nilai character:"+c); /* Prosedur baca dari standar input, berjalan di JAVA versi 1.5 keatas */ System.out.println("Contoh pembacaan dari standar input (berjalan di JAVA versi 1.5 keatas)"); Scanner sc = new Scanner(System.in); System.out.print("masukkan nilai int:");i=sc.nextInt(); System.out.print("masukkan nilai float:");f=sc.nextFloat(); System.out.print("masukkan nilai double:");d=sc.nextDouble(); System.out.print("masukkan nilai boolean:");b=sc.nextBoolean(); System.out.print(sc.nextLine()); System.out.print("masukkan nilai String:");s=sc.nextLine(); System.out.println(s); try{ System.out.print("masukkan nilai character:");c=(char)System.in.read(); }catch(IOException iex) { System.out.println(iex); } /* Prosedur tulis ke standar output */ System.out.println("nilai int:"+i); System.out.println("nilai float:"+f); System.out.println("nilai double:"+d); System.out.println("nilai boolean:"+b); System.out.println("nilai String:"+s); System.out.println("nilai character:"+c); } }

3. Instansiasi tanpa Objek dan Override


//utama.java class Foo { Foo (){ System.out.println("\nKonstruktor "); Foo(int x) { System.out.println("\nKonstruktor dg parameter"); } void f1(){ System.out.println("Fungsi F1"); }

public class utama { public static void main (String args[]) { (new Foo() { void f1(){ System.out.println("Fungsi 22222..."); } }).f1(); } }

4. Multiple Inheritance
// File testPanda.java // Contoh multiple inheritance dengan interface // dan Polymorhism // Herbivore interface Herbivore { public void Makan(); } class Bear { Bear () {System.out.println("Bear .."); } } class Panda extends Bear implements Herbivore { Panda() {System.out.println("Panda ..");} public void Makan () {System.out.println("Panda makan rumput .."); } } class testPanda { public static void main(String argv[]) { Bear B=new Bear();

Panda P=new Panda(); // Polymorphism Bear Lingling=new Panda(); } }

5. Kelas Abstrak
// File : testAbstract.java //KelasAbstract abstract class KelasAbstract { int i; abstract void operasi(); } class KelasRiil extends KelasAbstract { KelasRiil () { i=0; System.out.println("konstruktor Kelas Riil.."); } void operasi() { System.out.println("implementasi body di kelas riil"); } } class testAbstract { public static void main(String argv[]) { // tidak boleh // KelasAbstract KA; } } KelasRiil Kr= new KelasRiil();

6. Kelas Final
//kelas_final.java //contoh kelas final //class modifier 'abstract' tidak boleh ditambahkan pada kelas final // kenapa ?? final class kelas_final { int i; //prosedur abstract tidak boleh didef. di class final void increment(){ i++; } } //kelas final tidak dapat di extends atau diturunkan //deklarasi berikut tidak diperbolehkan //class anak extends kelas_final { // int j; //}

7. Baca Tulis File Teks


7.1. Menampilkan isi File Teks

//FileApp.java //Membaca dan menampilkan file teks import java.io.*; public class FileApp { public static void main(String args[]) { System.out.println(""); System.out.println("------------------------------"); System.out.println(""); try {

} catch (FileNotFoundException e) {

FileInputStream inputStream = new FileInputStream("test.java"); String str = ""; int b = 0; while(b != -1) { b = inputStream.read(); str += (char)b; } inputStream.close(); System.out.println(str);

System.out.println("File not found!"); } catch (IOException e) { System.out.println("I/O Error!"); } } } System.out.println("------------------------------");

7.2.

Menyalin File

//FOutputStream.java //Menyalin file asal (arg[0]) ke file tujuan (arg[1]) //dg Byte Stream import java.io.*; public class FOutputStream { public static void main(String args[]) throws IOException { if (args.length==2) { FileInputStream inputStream =

//

new FileInputStream(args[0]); FileOutputStream outputStream = new FileOutputStream(args[1]); int b = 0; while(b != -1) { b = inputStream.read(); outputStream.write((char)b); str += (char)b; } inputStream.close(); outputStream.close();

} }

7.3.

LineNumberReader

//LineNbReader.java //Membaca dan menampilkan file teks dg Char Stream (LineNumberReader) import java.io.*; public class LineNbReader { public static void main(String args[]) throws IOException { if (args.length==1) { String line_read; LineNumberReader source = new LineNumberReader ( new FileReader(args[0])); while (source.ready()) { line_read = source.readLine(); if (line_read!=null) System.out.println("["+ source.getLineNumber()+ "]:" + line_read); } source.close(); }

} }

7.4.

Scanner

//padanan ada pada file IO.java //(Di Java, nama file harus sama dengan nama kelas) import java.io.*; import java.util.Scanner; class IO { public static void main(String args[]) { //Jika ingin membaca dari file, ganti menjadi //Scanner sc = new Scanner(new FileInputStream("namafile")); Scanner sc = new Scanner(System.in);

} }

int x = sc.nextInt(); float f = sc.nextFloat(); //tidak ada next char pada kelas scanner //jika yang diperlukan adalah karakter, //maka ambil karakter pertama dalam string String s= sc.next(); System.out.printf("x = %d f = %f s = %s\n", x, f, s);

7.5.

Mesin Karakter

//padanan ada di MesinKar.java dan MesinKar2.java //pada MesinKar2.java, eksepsi ditangani dengan try dan catch // MesinKar2 belum direalisasi di sini import java.io.*; class MesinKar { public static void main(String argv[]) throws java.io.IOException { FileReader mesinkar = new FileReader("fin.txt"); FileWriter mesinrek = new FileWriter("fout.txt"); int cc = mesinkar.read(); while (cc!=-1){ mesinrek.write(cc); cc = mesinkar.read(); } mesinkar.close(); mesinrek.close(); } }

7.6.

Mesin Baris

//MesinBaris.java //akhir baris adalah jika kembalian readLine() sama dengan null import java.io.*; class MesinBaris { public static void main(String argv[]) throws IOException { FileReader filein = new FileReader("fin.txt"); BufferedReader br = new BufferedReader(filein); String s = br.readLine(); int nbaris = 0; while (s!=null) { nbaris++; System.out.println("string hasil baca= "+s); s = br.readLine(); } System.out.println("Banyaknya baris="+nbaris); filein.close(); } }

8. Pemakaian Library
8.1. Memecah String
//ada dua cara untuk melakukan pemecahan string //Cara pertama dengan classs StringTokenizer // (dapat digunakan di JDK sebelum 1.5) import java.io.*; import java.util.*; class BacaString1 { public static void main(String argv[]) { StringTokenizer st = new StringTokenizer("if you think Java is difficult ... "); while (st.hasMoreTokens()){ System.out.println(st.nextToken()); } } }

//cara kedua dengan kelas Scanner (JDK 1.5 ke atas) import java.io.*; import java.util.*; class BacaString2 { public static void main(String argv[]) { Scanner st = new Scanner(new StringReader("if you think Java is difficult ... ")); while (st.hasNext()){ System.out.println(st.next()); } } }

8.2.

Kelas MyDate

// ---------------------------------------------------------------------// DateExample.java // ---------------------------------------------------------------------/* * ===================================================================== ====== * Copyright (c) 1998-2005 Jeffrey M. Hunter. All rights reserved. * * All source code and material located at the Internet address of

* http://www.idevelopment.info is the copyright of Jeffrey M. Hunter, 2005 and * is protected under copyright laws of the United States. This source code may * not be hosted on any other site without my express, prior, written * permission. Application to host any of the material elsewhere can be made by * contacting me at jhunter@idevelopment.info. * * I have made every effort and taken great care in making sure that the source * code and other content included on my web site is technically accurate, but I * disclaim any and all responsibility for any loss, damage or destruction of * data or any other property which may arise from relying on it. I will in no * case be liable for any monetary damages arising from such loss, damage or * destruction. * * As with any code, ensure to test this code in a development environment * before attempting to run it in production. * ===================================================================== ==== */ import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; /** * ----------------------------------------------------------------------* Used to provide an example that exercises most of the functionality of the * java.util.Date class. A Date object represents a precise moment in time, * down to the millisecond. Dates are represented as a long that counts the * number of milliseconds since midnight, January 1, 1970, Greenwich Meantime. * * @version 1.0 * @author Jeffrey M. Hunter (jhunter@idevelopment.info) * @author http://www.idevelopment.info * ----------------------------------------------------------------------*/ public class MyDate { /** * Helper utility used to print * a String to STDOUT. * @param s String that will be printed to STDOUT. */ private static void prt(String s) { System.out.println(s); }

private static void prt() { System.out.println(); } private static void doDateExample() { // To create a Date object for the current // date and time use the noargs Date() constructor like this: prt("CURRENT DATE/TIME"); prt("======================================================="); Date now = new Date(); prt(" new Date() : " + now); prt(); // number of // Meantime // // // // To create a Date object for a specific time, pass the milliseconds since midnight, January 1, 1970, Greenwich to the constructor, like this: Establish a date object set in milliseconds relative to 1/1/1970 GMT

prt("DATE OBJECT FOR SPECIFIC TIME"); prt("======================================================="); Date specificDate1 = new Date(24L*60L*60L*1000L); Date specificDate2 = new Date(0L); prt(" new Date(24L*60L*60L*1000L) : " + specificDate1); prt(" new Date(0L) : " + specificDate2); prt(); // You can return the number of milliseconds in the Date // as a long, using the getTime() method. For example, // to time a block of code, you might do this prt("USE getTime() TO RETURN MILLISECONDS"); prt("======================================================="); Date startTime = new Date(); prt(" Start Time : " + startTime); // .... // Insert ant "timed code" here... // ... System.out.print(" "); for (int i = 0; i < 10000000; i++) { if ((i % 1000000) == 0) { System.out.print("."); } // More "timed" code } prt(); Date endTime = new Date(); prt(" End Time : " + endTime); long elapsed_time = endTime.getTime() - startTime.getTime(); prt("That took " + elapsed_time + " milliseconds"); prt();

10

of

// You can change a Date by passing the new date as a number

// milliseconds since midnight, January 1, 1970, GMT, to the setTime() // method, like this: prt("USE gsetTime() TO CHANGE A DATE OBJECT"); prt("======================================================="); Date changeDate = new Date(); prt(" new Date() : " + changeDate); changeDate.setTime(24L*60L*60L*1000L); prt(" setTime(24L*60L*60L*1000L) : " + changeDate); prt(); // The before() method returns true if this Date is before the Date // argument, false if it's not. // For example // if (midnight_jan2_1970.before(new Date())) { // The after() method returns true if this Date is after the Date // argument, false if it's not. // For example // if (midnight_jan2_1970.after(new Date())) { // The Date class also has the usual hashCode(), // equals(), and toString() methods. prt("COMPARE DATES USING: before(), after(), equals()"); prt("======================================================="); Date compareDateNow1 Date compareDateNow2 Date compareDate1970 = new Date(); = (Date) compareDateNow1.clone(); = new Date(24L*60L*60L*1000L);

prt(" Compare (Equals):"); prt(" - " + compareDateNow1); prt(" - " + compareDateNow2); if (compareDateNow1.equals(compareDateNow2)) { prt(" - The two dates are equal."); } else { prt(" - The two dates are NOT equal."); } prt(); prt(" Compare (Equals):"); prt(" - " + compareDateNow1); prt(" - " + compareDate1970); if (compareDateNow1.equals(compareDate1970)) { prt(" - The two dates are equal."); } else { prt(" - The two dates are NOT equal."); } prt(); prt(" Compare (Before):"); prt(" - " + compareDateNow1); prt(" - " + compareDate1970); if (compareDateNow1.before(compareDate1970)) {

11

prt(" - " + compareDateNow1 + " comes before " + compareDate1970 + "."); } else { prt(" - " + compareDateNow1 + " DOES NOT come before " + compareDate1970 + "."); } prt(); prt(" Compare (After):"); prt(" - " + compareDateNow1); prt(" - " + compareDate1970); if (compareDateNow1.after(compareDate1970)) { prt(" - " + compareDateNow1 + " comes after " + compareDate1970 + "."); } else { prt(" - " + compareDateNow1 + " DOES NOT come after " + compareDate1970 + "."); } prt();

prt("RETRIEVE MILLISECONDS"); prt("======================================================="); // Establish a date object set in milliseconds relative to 1/1/1970 GMT Date y = new Date(1000L*60*60*24); // Retrieve the number of milliseconds since 1/1/1970 GMT (31536000000) long n = y.getTime(); prt(" Number of milliseconds since 1/1/1970 (GMT) : " + n); // Computes a hashcode for the date object (1471228935) int i = y.hashCode(); prt(" Hash code for object //Retrieve the string representation of the date //(Thu Dec 31 16:00:00 PST 1970) String s = y.toString(); prt(" String representation of date prt(); prt("PARSE STRING TO DATE"); prt("================================================================ ="); Date newDate; String inputDate = "1994-02-14"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMdd"); System.out.print(" " + inputDate + " parses as "); try { newDate = formatter.parse(inputDate); prt(newDate + "."); } catch (ParseException e) { prt("Unparseable using " + formatter + "."); } prt();

: " + i);

: " + s);

12

} public static void main(String[] args) { prt(); doDateExample(); } }

8.3.

Program XML-IO

/* Nama File : XMLIO.java */ /* Nama Kelas : XMLIO */ /* Pembuat : Hananto Widhi */ /* Deskripsi :Contoh pembacaan dan penulisan file XML dg menggunakan DOM */ import import import import import import import import import import import import import import import import import import import import import javax.xml.parsers.DocumentBuilder; javax.xml.parsers.DocumentBuilderFactory; javax.xml.parsers.FactoryConfigurationError; javax.xml.parsers.ParserConfigurationException; javax.xml.transform.TransformerFactory; javax.xml.transform.Transformer; javax.xml.transform.TransformerException; javax.xml.transform.TransformerConfigurationException; javax.xml.transform.Source; javax.xml.transform.Result; javax.xml.transform.stream.StreamResult; javax.xml.transform.dom.DOMSource; org.xml.sax.SAXException; org.w3c.dom.Document; org.w3c.dom.Node; org.w3c.dom.NamedNodeMap; org.w3c.dom.NodeList; org.w3c.dom.DOMImplementation; org.w3c.dom.Element; org.w3c.dom.Text; org.w3c.dom.DOMException;

import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParseException; import java.io.IOException; import java.io.File; public class XMLIO { public static void saveToXMLFile(String filename) { Person personList[] = { new Person(23506002,"Andri Heryandi",new Date(),50.3f,true,new Point(1,5)), new Person(23506003,"Uuf BrajaWidagda",new Date(),45.9f,false,new Point(5,5)),

13

new Person(23506005,"Suprih Widodo",new Date(),55.0f,false,new Point(10,13)), new Person(23506006,"Eri Indrawan",new Date(),60.6f,true,new Point(13,25)), new Person(23506007,"M Fachrurrozi",new Date(),70.0f,true,new Point(17,35)), new Person(23506009,"Andri Mirandi",new Date(),75.0f,false,new Point(12,15)), new Person(23506011,"Renan Prasta Jenie",new Date(),49.5f,false,new Point(12,35)), new Person(23506013,"Anton Suherman",new Date(),55.6f,true,new Point(11,55)), new Person(23506014,"Lukman Talibo",new Date(),56.0f,false,new Point(12,25)), new Person(23506015,"Lukfi Halim",new Date(),70.2f,true,new Point(12,35)), new Person(23506017,"Djoni Setiawan Kartawihardja",new Date(),45.8f,true,new Point(21,65)) }; try {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); // Create the document Document doc = impl.createDocument(null, "PersonList", null); Element root = doc.getDocumentElement(); for (int i = 0; i < personList.length; i++) { Element person = doc.createElement("Person"); person.setAttribute("Id",Integer.toString(personList[i].getId())); person.setAttribute("Nama",personList[i].getNama()); person.setAttribute("TglLahir",(new SimpleDateFormat()).format(personList[i].getTanggal())); person.setAttribute("BeratBadan",Float.toString(personList[i].getBera tBadan())); person.setAttribute("Aktif",Boolean.toString(personList[i].getAktif() )); Element tpoint = doc.createElement("Posisi"); tpoint.setAttribute("Absis",Integer.toString(personList[i].getPosisi( ).getAbsis())); tpoint.setAttribute("Ordinat",Integer.toString(personList[i].getPosis i().getOrdinat())); person.appendChild(tpoint); root.appendChild(person);

14

} // Serialize the document onto System.out TransformerFactory xformFactory = TransformerFactory.newInstance(); Transformer idTransform = xformFactory.newTransformer(); Source input = new DOMSource(doc); Result output = new StreamResult(new File(filename)); idTransform.transform(input, output); }catch (FactoryConfigurationError e) { System.out.println("Could not locate a JAXP factory class"); }catch (ParserConfigurationException e) { System.out.println("Could not locate a JAXP DocumentBuilder class"); }catch (DOMException e) { System.err.println(e); }catch (TransformerConfigurationException e) { System.err.println(e); }catch (TransformerException e) { System.err.println(e); } } public static void readFromXMLFile(String filename) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { File f = new File(filename); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(f); NodeList nodelist = document.getElementsByTagName("Person"); Person[] personList = new Person[nodelist.getLength()]; for (int i=0;i<nodelist.getLength();i++) { personList[i] = new Person(); NamedNodeMap attrs = nodelist.item(i).getAttributes(); personList[i].setId(Integer.parseInt(attrs.getNamedItem("Id").getNode Value())); personList[i].setNama(attrs.getNamedItem("Nama").getNodeValue()); try{ personList[i].setTanggal((new SimpleDateFormat()).parse(attrs.getNamedItem("TglLahir").getNodeValue ())); }catch (ParseException e) { System.out.println(e); } personList[i].setBeratBadan(Float.parseFloat(attrs.getNamedItem("Bera tBadan").getNodeValue()));

15

personList[i].setAktif(Boolean.parseBoolean(attrs.getNamedItem("Aktif ").getNodeValue())); Point pos = new Point(); pos.setAbsis(Integer.parseInt(nodelist.item(i).getFirstChild().getAtt ributes().getNamedItem("Absis").getNodeValue())); pos.setOrdinat(Integer.parseInt(nodelist.item(i).getFirstChild().getA ttributes().getNamedItem("Ordinat").getNodeValue())); personList[i].setPosisi(pos); } for (int i=0;i<personList.length;i++) { System.out.println(personList[i]); } } catch (SAXException sxe) { sxe.printStackTrace(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); }

public static void main(String args[]) { if (args.length!=2) { System.out.println("usage:"); System.out.println("create XML file type: java XMLIO -o filename.xml"); System.out.println("read XML file type: java XMLIO -i filename.xml"); return; } if (args[0].equals("-i")) { readFromXMLFile(args[1]); }else if (args[0].equals("-o")) { saveToXMLFile(args[1]); } } }

Data
<?xml version="1.0" encoding="UTF-8"?> <PersonList><Person Aktif="true" BeratBadan="50.3" Id="23506002" Nama="Andri Heryandi" TglLahir="12/26/06 7:56 AM"><Posisi Absis="1" Ordinat="5"/></Person> <Person Aktif="false" BeratBadan="45.9" Id="23506003" Nama="Uuf BrajaWidagda" TglLahir="12/26/06 7:56 AM"><Posisi Absis="5" Ordinat="5"/></Person> <Person Aktif="false" BeratBadan="55.0" Id="23506005" Nama="Suprih Widodo" TglLahir="12/26/06 7:56 AM"><Posisi Absis="10" Ordinat="13"/></Person>

16

<Person Aktif="true" BeratBadan="60.6" Id="23506006" Nama="Eri Indrawan" TglLahir="12/26/06 7:56 AM"><Posisi Absis="13" Ordinat="25"/></Person> <Person Aktif="true" BeratBadan="70.0" Id="23506007" Nama="M Fachrurrozi" TglLahir="12/26/06 7:56 AM"><Posisi Absis="17" Ordinat="35"/></Person> <Person Aktif="false" BeratBadan="75.0" Id="23506009" Nama="Andri Mirandi" TglLahir="12/26/06 7:56 AM"><Posisi Absis="12" Ordinat="15"/></Person> <Person Aktif="false" BeratBadan="49.5" Id="23506011" Nama="Renan Prasta Jenie" TglLahir="12/26/06 7:56 AM"><Posisi Absis="12" Ordinat="35"/></Person> <Person Aktif="true" BeratBadan="55.6" Id="23506013" Nama="Anton Suherman" TglLahir="12/26/06 7:56 AM"><Posisi Absis="11" Ordinat="55"/></Person> <Person Aktif="false" BeratBadan="56.0" Id="23506014" Nama="Lukman Talibo" TglLahir="12/26/06 7:56 AM"><Posisi Absis="12" Ordinat="25"/></Person> <Person Aktif="true" BeratBadan="70.2" Id="23506015" Nama="Lukfi Halim" TglLahir="12/26/06 7:56 AM"><Posisi Absis="12" Ordinat="35"/></Person> <Person Aktif="true" BeratBadan="45.8" Id="23506017" Nama="Djoni Setiawan Kartawihardja" TglLahir="12/26/06 7:56 AM"><Posisi Absis="21" Ordinat="65"/></Person> </PersonList>

17

Vous aimerez peut-être aussi