Senin, 28 Oktober 2013

MODUL 2



MODUL 2
Oleh :

RUDI HARTANTO
135623053

DIII MANAJEMEN INFORMATIKA

TEKNIK ELEKTRO

UNIVERSITAS NEGERI SURABAYA


2013

A.     DASAR TEORI
1.      Netbeans dan Eclipse

Pada 1991, sekelompok insinyur Sun dipimpin oleh Patrick Naughton dan James Gosling ingin merancang bahasa komputer untuk perangkat konsumer seperti cable TV Box. Dikarenakan perangkat tersebut tidak memiliki banyak memori, bahasa harus berukuran kecil dan mengandung kode yang liat. Juga karena manufakturmanufaktur berbeda memilih processor yang berbeda pula, maka bahasa harus bebas dari manufaktur manapun. Proyek diberi nama kode ”Green”.
Kebutuhan untuk fleksibilitas, kecil, liat dan kode yang netral terhadap platform mengantar tim mempelajari implementasi Pascal yang pernah dicoba. Niklaus Wirth, pencipta bahasa Pascal telah merancang bahasa portabel yang menghasilkan intermediate code untuk mesin hipotesis. Mesin ini sering disebut dengan mesin maya (virtual machine). Kode ini kemudian dapat digunakan di sembarang mesin yang memiliki interpreter. Proyek Green menggunakan mesin maya untuk mengatasi isu utama tentang netral terhadap arsitektur mesin.
Karena orang–orang di proyek Green berbasis C++ dan bukan Pascal maka kebanyakan sintaks diambil dari C++, serta mengadopsi orientasi objek dan bukan prosedural. Mulanya bahasa yang diciptakan diberi nama ”Oak” oleh James Gosling yang mendapat inspirasi dari sebuah pohon yang berada pada seberang kantornya, namun dikarenakan nama Oak sendiri merupakan nama bahasa pemrograman yang telah ada sebelumnya, kemudian SUN menggantinya dengan JAVA. Nama JAVA sendiri terinspirasi pada saat mereka sedang menikmati secangkir kopi di sebuah kedai kopi yang kemudian dengan tidak sengaja salah satu dari mereka menyebutkan kata JAVA yang mengandung arti asal bijih kopi. Akhirnya mereka sepakat untuk memberikan nama bahasa pemrograman tersebut dengan nama Java.
Java telah mengakomodasi hampir seluruh fitur penting bahasa–bahasa pemrograman yang ada semenjak perkembangan komputasi modern manusia :
1.    Dari SIMULA, bahasa pada tahun 65-an, bahasa yang paling mempengaruhi Java sekaligus C++. Dari bahasa ini diadopsi bentukan–bentukan dasar dari pemrograman berorientasi objek.
2.    Dari LISP – bahasa tahun 55-an. Diadopsi fasilitas garbage collection, serta kemampuan untuk meniru generic list processing, meski fasilitas ini jarang yang memanfaatkannya.
3.    Dari Algol – bahasa pada tahun 60-an, diambil struktur kendali yang dimilikinya.
4.    Dari C++, diadopsi sintaks, sebagian semantiks dan exception handling
5.    Dari bahasa Ada, diambil strongly type, dan exception handling.
6.    Dari Objective C, diambil fasilitas interface.
7.    Dari bahasa SmallTalk, diambil pendekatan single-root class hiérarchie, dimana object adalah satu kesatuan hirarki pewarisan
8.    Dari bahasa Eiffel, fasilitas assertion yang mulai diterapkan di sebagian JDK 1.4





2.      Penulisan Program di Java, Input, Output
Sekarang, kita akan mencoba untuk menganalisa program Java pertama :
public class Hello
{
/**
* My first java program
*/
public static void main(String[] args)
{
//menampilkan string ”Hello world” pada layar
System.out.println("Hello world!");
}
}
Baris pertama kode :

public class Hello

menandakan nama class yaitu Hello. Dalam Java, semua kode seharusnya ditempatkan di dalam deklarasi class. kita melakukannya dengan menggunakan kata kunci class. Sebagai tambahan, class menggunakan access specifier public, yang mengindikasikan bahwa class kita mempunyai akses bebas ke class yang lain dari package yang lain pula (package merupakan kumpulan class-class). Kita akan membahas lebih dalam mengenai package dan access specifier pada pembahasan selanjutnya.
Baris berikutnya yaitu yang terdiri atas kurung kurawal { menandakan awal blok. Pada kode ini, kita menempatkan kurung kurawal pada baris selanjutnya setelah deklarasi class, bagaimanapun, kita dapat juga meletakkan kurung kurawal ini setelah baris pertama dari kode yang kita tulis. Jadi, kita dapat menulis kode kita sebagai berikut :

public class Hello
{
atau
public class Hello {

Tiga baris selanjutnya menandakan adanya komentar Java. Komentar adalah sesuatu yang digunakan untuk mendokumentasikan setiap bagian dari kode yang ditulis. Komentar bukan merupakan bagian dari program itu sendiri, tetapi digunakan untuk tujuan dokumentasi. Komentar itu sendiri dapat ditambahkan pada kode yang Anda tulis sebagai petunjuk yang dapat membantu proses pembelajaran pemrograman yang baik.

/**
* My first java program
*/

Komentar dinyatakan dengan tanda “/*” dan “*/”. Segala sesuatu yang ada diantara tanda tersebut diabaikan oleh compiler Java, dan mereka hanya dianggap sebagai komentar. Baris selanjutnya,

public static void main(String[] args){
atau dapat juga ditulis sebagai berikut,
public static void main(String[] args)
{
mengindikasikan nama suatu method dalam class Hello yang bertindak sebagai method utama. Method utama adalah titik awal dari suatu program Java. Semua program kecuali applet yang ditulis dalam bahasa Java dimulai dengan method utama. Yakinkan untuk mengikuti kaidah penulisan tanda yang benar. Baris selanjutnya juga merupakan komentar,

//Menampilkan string "Hello world" pada layar
Sekarang kita mempelajari 2 cara untuk membuat komentar. Cara pertama adalah dengan menempatkan komentar dalam /* dan */, dan cara yang lain adalah dengan menuliskan tanda // pada awal komentar

System.out.println("Hello world!");

menampilkan teks “Hello World!” pada layar. Perintah System.out.println(), menampilkan teks yang diapit oleh tanda double pute (“ ”) pada layar.
Dua baris terakhir yang terdiri atas dua kurung kurawal digunakan untuk menutup method utama dan masing-masing class secara berurutan.

3.      Operator: Assigment, Matematika, Perbandingan, Logika
Assignment, Arithmetic, and Unary Operators
The Simple Assignment Operator
One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:
 int cadence = 0;
 int speed = 0;
 int gear = 1;
This operator can also be used on objects to assign object references, as discussed in Creating Objects.
The Arithmetic Operators
The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result.
+       additive operator (also used for
        String concatenation)
-       subtraction operator
*       multiplication operator
/       division operator
%       remainder operator
The following program, ArithmeticDemo, tests the arithmetic operators.

class ArithmeticDemo {

    public static void main (String[] args){
        
        // result is now 3
        int result = 1 + 2;
        System.out.println(result);

        // result is now 2
        result = result - 1;
        System.out.println(result);

        // result is now 4
        result = result * 2;
        System.out.println(result);

        // result is now 2
        result = result / 2;
        System.out.println(result);

        // result is now 10
        result = result + 8;
        // result is now 3
        result = result % 7;
        System.out.println(result);
    }
}
You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.
The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program:

class ConcatDemo {
    public static void main(String[] args){
        String firstString = "This is";
        String secondString = " a concatenated string.";
        String thirdString = firstString+secondString;
        System.out.println(thirdString);
    }
}
By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output.
The Unary Operators
The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.
+       Unary plus operator; indicates
        positive value (numbers are
        positive without this, however)
-       Unary minus operator; negates
        an expression
++      Increment operator; increments
        a value by 1
--      Decrement operator; decrements
        a value by 1
!       Logical complement operator;
        inverts the value of a boolean
The following program, UnaryDemo, tests the unary operators:

class UnaryDemo {

    public static void main(String[] args){
        // result is now 1
        int result = +1;
        System.out.println(result);
        // result is now 0
        result--;
        System.out.println(result);
        // result is now 1
        result++;
        System.out.println(result);
        // result is now -1
        result = -result;
        System.out.println(result);
        boolean success = false;
        // false
        System.out.println(success);
        // true
        System.out.println(!success);
    }
}
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.
The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:

class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++;
        // prints 4
        System.out.println(i);
        ++i;                                  
        // prints 5
        System.out.println(i);
        // prints 6
        System.out.println(++i);
        // prints 6
        System.out.println(i++);
        // prints 7
        System.out.println(i);
    }
}
4.      Tingkatan Operator

Operator
            Operator adalah karakter khusus yang memerintahkan compiler untuk melakukan operasi terhadap sejumlah operand . Perintah operasi dispesifikasikan oleh operator yang operandnya berupa variabel , pernyataan atau konstanta
            Menurut tempatnya dan Operand yang diproses, operator dibagi menjadi 5 yaitu :
·          Operator unary : Operator yang mengolah satu operand
·          Operator prefix : Operator yang ditempatkan sebelum operand
·          Operator biner infiks : Operator yang ditempatkan diantara dua operand
·          Operator postfiks : Operator yang ditempatkan setelah operand .
·          Operator ternary : Operator yang membutuhkan tiga operand
            Menurut jenisnya operator dasar Java ada 4 yaitu : aritmatika, bitwise,relasi dal logika.

Operator dan Aritmatika
            Digunakan untuk proses matematika . Operator aritmatika tidak bisa digunakan untuk tipe Boolean tetapi dapat digunakan pada tipe char . Anggota dari operator aritmatika sebagai berikut :
Operator
Hasil
+
Penjumlahan
+=
Persamaan Penjumlahan
-
Pengurangan ( unary minus )
-=
Persamaan Pengurangan
*
Perkalian
*=
Persamaan Perkalian
/
Pembagian
/=
Persamaan Pembagian
%
Modulus (Sisa Pembagian)
%=
Persamaan Modulus
++
Penambahan
--
Pengurangan


Contoh :
int a = 1 + 1;
int b = a * 5;
int c = b / 10;
int d = c - 1;
int e = -a;
int x = 42 % 10; //Modulus/Pembagian sisa nilai x =2

i+ = 4; //artinya i = i + 4
j- = 2; //artinya j = j - 2
k* = 3; //artinya k = k * 3
a/ = 2; //artinya a = a/2
b% = 2; //artinya b = b % 2

Operator Bitwise Integer
            Tipe numeric integer : long , int , short , char dan byte memiliki operator tambahan yang dapat memodifikasi dan memeriksa bit bit yang menyusun nilainya. Operatornya adalah sebagai berikut :
Operator
Hasil
~
Unary Not
&
AND
|
OR
^
Exclusive OR
>> 
Shift kanan
>>> 
Shift kanan , isi dengan nol
<< 
Shift kiri
&=
Pernyatataan AND
|=
Pernyataan OR
^=
Pernyataan exclusive OR
>>=
Pernyataan shift kanan
>>>=
Pernyataan shift kanan , isi dengan nol
<<=
Pernyataan shift kiri

            Operator bitwise mengkonversi bilangan decimal ke dalam bentuk biner kemudian dimanipulasi sesuai dengan operatornya . Contoh :
10 diubah menjadi 1010
~10 hasilnya : NOT 1010 = 0101 ( membalikkan / invers semua bit )
10 & 2 =          1010                            10|2=              1010
                        0010                                                    0010
                                    _____ &                                              ____ |
                        0010                                                    1010




Operator Relasi
            Digunakan untuk membandingkan dua buah nilai , yang dijabarkan pada table berikut :
Operator
Hasil
==
Sama dengan
!=
Tidak sama dengan
Lebih besar dari
Lebih kecil dar
>=
Lebih besar sama dengan
<=
Lebih kecil sama dengan

Semua operator diatas akan menghasilkan nlai Boolean (true dan false ) contoh :

int a = 4
int b = 2
Boolean c = a < b; // c bernilai false

Operator Logika Boolean
            Operator ini bekerja pada operand Boolean , yang akan memanipulasi nilai Boolean untuk menghasilkan nilai Boolean pula , contoh :
Operator
Hasil
&
Logika AND
|
Logika OR
^
Logika XOR
||
Hubungan – singkat OR
&&
Hubungan – singkat AND
!
Hubungan – singkat NOT
&=
Pernyataan AND
!=
Pernyataan OR
^=
Pernyataan XOR
==
Sama Dengan
!=
Tidak sama dengan
?:
Operator tenary if-then-else

Boolean q=true;
Boolean b=false;
Boolean c=a | b;
Boolean d=a & b;

            Operator hubungan singkat ( short circuit logical operator) digunakan apabila ada dua operan ( operan kanan dan operan kiri ) dimana operan kanan bergantung pada operan kiri, baik true maupun false.
            Contoh : if 9 denom ! = 0 && num / denom > 10)
            Keterangan :
*      Bila nilai denom = 0 , maka nilainya adalah false sehingga operan kanan tidak akan diperiksa karena hasilnya false sesuai dengan operan kiri.
*      Bila nilai denom !=0 , maka nilainya adalah true dan perlu di ANDkan dengan num/denom >10, sehingga operan kiri dan kanan perlu diANDkan untuk mengetahui hasil logikanya (TRUE atau FALSE)
            Operator Ternary if – then – else membutuhkan 3 parameter yang bentuknya adalah sebagai berikut ;
Expression ? statement1 : statemen2
            Keterangan : Expression berupa pernyataan yang memeriksa besaran Boolean . Jika hasilnya true maka statement1 dijalankan , sebaliknya jika hasilnya false maka statemen2 dijalankan . Syaratnya statement1 dan 2 harus menghasilkan tipe yang sama dan tidak boleh void.
Contoh:
Ratio = denom == 0 ? 0 : num / denom;
Ketika dijalankan Java akanmemeriksa pernyataan disebalah kiri ? ( denom == 0) , jiks denom = 0 maka pernyataan diantara tanda tanda ? dan : akan diperiksa dan ditetapkan sebagai hasil / nilai Ratio, sebaliknya jika tidak sama dengan 0 maka pernyataan num/ denom yang ditetapkan sebagai hasil / nila Ratio.

Preseden Operator
            Preseden operator menunjukkan adanya urutan tingkatan operator ( hirarki) yang penjabarannya pada table berikut :
tertinggi
( )
[ ]


++
--
~
!
*
/
%

+
-


>> 
>>> 
<< 

>=
<=
==
!=


&



^



|



&&



||



? :



terendah


5.      Percabangan (if, if....else, if...elseif...., switch)
The if-then and if-then-else Statements
The if-then Statement
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows:
void applyBrakes() {
    // the "if" clause: bicycle must be moving
    if (isMoving){
        // the "then" clause: decrease current speed
        currentSpeed--;
    }
}
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:
void applyBrakes() {
    // same as above, but without braces
    if (isMoving)
        currentSpeed--;
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.
The if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.
void applyBrakes() {
    if (isMoving) {
        currentSpeed--;
    } else {
        System.err.println("The bicycle has already stopped!");
    }
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.

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

        int testscore = 76;
        char grade;

        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}
The output from the program is:
    Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.
The switch Statement
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
The following code example, SwitchDemo, declares an int named month whose value represents a month. The code displays the name of the month, based on the value of month, using the switch statement.

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

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}
In this case, August is printed to standard output.
The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.
You could also display the name of the month with if-then-else statements:
int month = 8;
if (month == 1) {
    System.out.println("January");
} else if (month == 2) {
    System.out.println("February");
}
...  // and so on
Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.
Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year:

public class SwitchDemoFallThrough {

    public static void main(String[] args) {
        java.util.ArrayList<String> futureMonths =
            new java.util.ArrayList<String>();

        int month = 8;

        switch (month) {
            case 1:  futureMonths.add("January");
            case 2:  futureMonths.add("February");
            case 3:  futureMonths.add("March");
            case 4:  futureMonths.add("April");
            case 5:  futureMonths.add("May");
            case 6:  futureMonths.add("June");
            case 7:  futureMonths.add("July");
            case 8:  futureMonths.add("August");
            case 9:  futureMonths.add("September");
            case 10: futureMonths.add("October");
            case 11: futureMonths.add("November");
            case 12: futureMonths.add("December");
                     break;
            default: break;
        }

        if (futureMonths.isEmpty()) {
            System.out.println("Invalid month number");
        } else {
            for (String monthName : futureMonths) {
               System.out.println(monthName);
            }
        }
    }
}
This is the output from the code:
August
September
October
November
December
Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections.
The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The code example calculates the number of days in a particular month:

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

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1: case 3: case 5:
            case 7: case 8: case 10:
            case 12:
                numDays = 31;
                break;
            case 4: case 6:
            case 9: case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) &&
                     !(year % 100 == 0))
                     || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = "
                           + numDays);
    }
}
This is the output from the code:
Number of Days = 29
Using Strings in switch Statements
In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month:

public class StringSwitchDemo {

    public static int getMonthNumber(String month) {

        int monthNumber = 0;

        if (month == null) {
            return monthNumber;
        }

        switch (month.toLowerCase()) {
            case "january":
                monthNumber = 1;
                break;
            case "february":
                monthNumber = 2;
                break;
            case "march":
                monthNumber = 3;
                break;
            case "april":
                monthNumber = 4;
                break;
            case "may":
                monthNumber = 5;
                break;
            case "june":
                monthNumber = 6;
                break;
            case "july":
                monthNumber = 7;
                break;
            case "august":
                monthNumber = 8;
                break;
            case "september":
                monthNumber = 9;
                break;
            case "october":
                monthNumber = 10;
                break;
            case "november":
                monthNumber = 11;
                break;
            case "december":
                monthNumber = 12;
                break;
            default:
                monthNumber = 0;
                break;
        }

        return monthNumber;
    }

    public static void main(String[] args) {

        String month = "August";

        int returnedMonthNumber =
            StringSwitchDemo.getMonthNumber(month);

        if (returnedMonthNumber == 0) {
            System.out.println("Invalid month");
        } else {
            System.out.println(returnedMonthNumber);
        }
    }
}
The output from this code is 8.
The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used. In order for the StringSwitchDemo example to accept any month regardless of case, month is converted to lowercase (with the toLowerCase method), and all the strings associated with the case labels are in lowercase.
Note: This example checks if the expression in the switch statement is null. Ensure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.
The while and do-while Statements
The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:
while (expression) {
     statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:

class WhileDemo {
    public static void main(String[] args){
        int count = 1;
        while (count < 11) {
            System.out.println("Count is: " + count);
            count++;
        }
    }
}
You can implement an infinite loop using the while statement as follows:
while (true){
    // your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed as follows:
do {
     statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:

class DoWhileDemo {
    public static void main(String[] args){
        int count = 1;
        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 11);
    }
}

The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination;
     increment) {
    statement(s)
}
When using this version of the for statement, keep in mind that:
·         The initialization expression initializes the loop; it's executed once, as the loop begins.
·         When the termination expression evaluates to false, the loop terminates.
·         The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:

class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
// infinite loop
for ( ; ; ) {
   
    // your code goes here
}
The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:

class EnhancedForDemo {
    public static void main(String[] args){
         int[] numbers =
             {1,2,3,4,5,6,7,8,9,10};
         for (int item : numbers) {
             System.out.println("Count is: " + item);
         }
    }
}
In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We recommend using this form of the for statement instead of the general form whenever possible.
Branching Statements
The break Statement
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop, as shown in the following BreakDemo program:
class BreakDemo {
    public static void main(String[] args) {

        int[] arrayOfInts =
            { 32, 87, 3, 589,
              12, 1076, 2000,
              8, 622, 127 };
        int searchfor = 12;

        int i;
        boolean foundIt = false;

        for (i = 0; i < arrayOfInts.length; i++) {
            if (arrayOfInts[i] == searchfor) {
                foundIt = true;
                break;
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at index " + i);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}
This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the statement after the for loop. This program's output is:
Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search"):

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

        int[][] arrayOfInts = {
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}
This is the output of the program.
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
The continue Statement
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.

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

        String searchMe = "peter piper picked a " + "peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;

        for (int i = 0; i < max; i++) {
            // interested only in p's
            if (searchMe.charAt(i) != 'p')
                continue;

            // process p's
            numPs++;
        }
        System.out.println("Found " + numPs + " p's in the string.");
    }
}
Here is the output of this program:
Found 9 p's in the string.
To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop.

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

        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;

        int max = searchMe.length() -
                  substring.length();

    test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
                break test;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}
Here is the output from this program.
Found it
The return Statement
The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value.
return;
The Classes and Objects lesson will cover everything you need to know about writing methods.

B. Soal Praktikum
1.       Tuliskan algoritma untuk mencari sisi miring dari suatu segitiga siku-siku jika diketahui diketahui panjang dua sisi yang membentuk sudut siku-siku.
Petunjuk: sisi miring segitiga siku-siku dapat dihitung dengan rumus pythagoras, 

2.       Tuliskan algoritma untuk menampilkan banyaknya pecahan uang paling efisien dari sejumlah uang yang di inputkan oleh pengguna.
Pecahan uang yang digunakan: 100.000, 50.000, 20.000, 10.000, 5.000, 2.000, 1.000, 500, 200, dan 100.
Contoh, untuk uang Rp 12.500, diperlukan 1 lembar 10.000, 1 lembar 2.000, dan 1 koin 500.
Input             : jumlah uang
Output         : banyaknya pecahan uang

3.       Buat algoritma untuk mengkonversi bilangan dalam format desimal menjadi biner.
Input             : bilangan desimal
Output         : bilangan biner
Ilustrasi:
http://pad3.whstatic.com/images/thumb/d/d1/Convert-from-Decimal-to-Binary-Step-14.jpg/550px-Convert-from-Decimal-to-Binary-Step-14.jpg


4.       Untuk menentukan bonus pegawai, berdasarkan ketentuan yang diberikan oleh bagian personalia dan keuangan sebagai berikut : Pegawai perusahaan digolongkan menjadi dua golongan, yaitu staf dan non staf. Staf akan mendapatkan bonus sebesar 1 juta rupiah dengan syarat bahwa ia telah bekerja paling tidak 5 tahun dan umurnya sudah mencapai 50 tahun; staf yang bekerja kurang dari 5 tahun dan berapapun umurnya, hanya mendapat bonus sebesar Rp. 500.000. Pegawai non staf yang telah bekerja lebih dari 5 tahun akan mendapat bonus sebesar Rp. 400.000 jika berumur lebih dari 50 tahun sedangkan pegawai non staf yang berumur kurang dari 50 tahun hanya mendapat bonus Rp. 250.000. Pegawai staf yang umurnya kurang dari 50 tahun akan mendapat bonus Rp. 300.000.

Buat algoritmanya?

5.       Tarif pemasangan iklan baris di sebuah Surat Kabar ditentukan sebagai berikut :
-       Hari        : Minggu, Senin, Selasa, Rabu, Kamis dan Jumat, per baris Rp. 33.000,-
-       Hari        : Sabtu, per baris Rp. 40.000,-
Buatlah algoritma untuk menghitung total biaya iklan baris yang harus dibayar oleh pengiklan.
Input     :               -  Hari (Minggu, Senin, Selasa, Rabu, Kamis, Jumat atau Sabtu)
                                -  Jumlah baris yang dipakai
Output :               Total biaya iklan yang harus dibayar pengiklan

Tuliskan algoritma untuk kasus diatas dalam bentuk flowchart.

6.       Info Harga Tiket Masuk bioskop Surabaya City adalah sebagai berikut :
-       Senin – Kamis                    : Rp 15.000,-
-       Jumat s/d Minggu            : Rp 35.000,-
-       Hari Libur                             : Rp 35.000,-
Input     :               -  Hari (Minggu, Senin, Selasa, Rabu, Kamis, Jumat atau Sabtu)
-  Libur atau Tidak Libur
-  Jumlah tiket yang dibeli
                Output : Total biaya tiket

Pertanyaan: Buat algoritma untuk menghitung total biaya tiket .

7.       Di sebuah perbelanjaan di Surabaya diadakan Pekan Diskon, dimana perhitungan bonus dihitung bertingkat untuk total belanja senilai :
-          Rp. 150.000,-                                      diskonnya : 10%
-          Rp. 275.000,-                                      diskonnya : 15%
-          Rp. 300.000,-                                      diskonnya : 20%
-          Rp. 400.000,-  ke atas                      diskonnya : 25%
Diskon tidak dihitung sebagai akumulasi dari diskon nilai belanja dibawahnya.
Buatlah algoritma untuk menghitung berapa nilai yang harus dibayar oleh pelanggan dengan total nilai belanja tertentu bila disertakan pula perhitungan diskonnya.
Input            : Total nilai belanja.
Output        : Nilai Diskon (dalam rupiah/bukan persen), Nilai yang harus dibayar

8.       Berikut ini adalah ketentuan untuk menghitung nilai, dan konversi menjadi nilai huruf.
Ketentuannya:
Nilai=((rata-rata tugas*30%)+(UTC*30%)+(UAC*40%))
Input             = tugas1,tugas2,tugas3,UTC,UAC
Output         = Nilai Akhir dan Nilai Huruf.
‘A’          jika nilai > 80 dan nilai <= 100
‘AB’    
   jika nilai > 70 dan nilai <= 80
‘B’           jika nilai > 65 dan nilai <= 70
‘BC’        jika nilai > 60 dan nilai <= 65
‘C’           jika nilai > 55 dan nilai <= 60
’D’          jika nilai > 40 dan nilai <= 55
’E’           jika nilai > 0 dan nilai <= 40

9.       Berikut ini adalah tarif pemakaian Air PDAM Kota Surabaya
Jumlah Pemakaian (m3)                Harga/m3
Pemakaian I       (     <  50 m3)        Rp.         200,-
Pemakaian II      (    51 – 150 )                         Rp.     500,-
Pemakaian III     ( 151 – 300 )                         Rp. 1.000,-
Pemakaian I V    ( >  300 m3 )                         Rp.  1.500,-

Input     : Jumlah Pemakaian
Output : Besar biaya yang harus dibayar

Jumlah Pemakaian  = 500 m3
Pemakaian I       (  s/d  50 m3)                   Rp.    200,-    *        50    =                 Rp. 10.000,-
Pemakaian II      (    51 – 150 )                   Rp.     500,-    *      100    =                 Rp. 50.000,-
Pemakaian III     ( 151 – 300 )                   Rp. 1.000,-    *      150    =               Rp. 150.000,-
Pemakaian IV    (  >  300 m3 )                   Rp.  1.500,-    *      200    =               Rp. 300.000,-
Biaya Total                                                                                                                          Rp. 510.000,-

Pertanyaan: Buat algoritma untuk kasus diatas.

10.   Sebuah perusahaan kartu kredit memberikan cash back kepada nasabahnya berdasarkan jumlah nilai pemakaian kartu kredit selama sebulan.
Nilai pemakaian                            cash back
---------------------  ----------
s.d 1.000.000                                                5%
1.000.000 – 10.000.000                             6%
10.000.000 – 25.000.000          7%
Diatas 25.000.000                        8%

Ilustrasi: seorang nasabah yang total pemakaian selama sebulan 18.000.000, maka cash backnya= 5%x1.000.000+6%x9.000.000+7%x8.000.000 = 160.000

Buat algoritma untuk menghitung cash back yang diterima nasabah berdasarkan nilai pemakaian kartu kredit.

C. PSOUDOCODE
a. Soal 1 Pythagoras
Deskripsi
hasil , sisi1, sisi2 : Double
Implementasi
hasil : C= √(a*a)+(b*b)
Output(hasil)
End.
b. Soal 2 Pecahan Uang
Deskripsi
seratusribu, limapuluhribu, duapuluhribu, sepuluhribu, limaribu, duaribu, seribu, limaratus, duaratus, seratus, inputuang, sisa : Integer
Implementasi
seratusribu = inputuang/100000;
sisa =inputuang - (seratusribu*100000);
limapuluhribu =sisa / 50000;
sisa =sisa - (limapuluhribu * 50000);
duapuluhribu =sisa / 20000;
sisa =sisa - (duapuluhribu * 20000);
sepuluhribu =sisa / 10000;
sisa =sisa - (sepuluhribu * 10000);
limaribu =sisa / 5000;
sisa =sisa - (limaribu * 5000);
duaribu =sisa / 2000;
sisa =sisa - (duaribu * 2000);
seribu =sisa / 1000;
sisa =sisa - (seribu * 1000);
limaratus =sisa / 500;
sisa =sisa - (limaratus * 500);
seratus =sisa / 100;
sisa =sisa - (seratus * 100);
if inputuang >= 100000 then
if seratusribu == 0 then
Output (“ ”)
else
Output (seratusribu)
endif
endif
if inputuang >= 50000 then
if limapuluhribu == 0 then
Output (“ ”)
else
Output (limapuluhribu)
endif
endif
if inputuang >= 20000 then
if duapuluhribu == 0 then
Output (“ ”)
else
Output (duapuluhribu)
endif
endif
if inputuang >= 10000 then
if sepuluhribu == 0 then
Output (“ ”)
else
Output (sepuluhribu)
endif
endif
if inputuang >= 5000 then
if limaribu == 0 then
Output (“ ”)
else
Output (limaribu)
endif
endif
if inputuang >= 2000 then
if duaribu == 0 then
Output (“ ”)
else
Output (duaribu)
endif
endif
if inputuang >= 1000 then
if seribu == 0 then
Output (“ ”)
else
Output (seribu)
endif
endif
if inputuang >= 500 then
if limaratus == 0 then
Output (“ ”)
else
Output (limaratus)
endif
endif
if inputuang >= 100 then
if seratus == 0 then
Output (“ ”)
else
Output (seratus)
endif
endif
if inputuang >= 0 then
Output (sisa)
End if
End.
c. Soal 3 Bilangan Desimal ke Biner
Deskripsi
bilangan , hasil=0 , i=0 : Integer
Implementasi
While bilangan>0 Repeat
hasil+=bilangan mod 2 * (int) Math.pow(10, i);
bilangan/=2;
i++;
Output (hasil)
End.
d. Soal 4 Bonus Pegawai
Deskripsi
nama, pegawai : String
masakerja, umur : Integer
Implementasi
If pegawai = staf then
If masakerja >=5 and umur >=50 then
Output (bonus)
Else if masakerja < 5 And umur = umur then
Output (bonus)
Else if masakerka = masakerja And umur < 50 then
Output (bonus)
End if
Else If pegawai = nonstaf then
If masakerja >= 5 And umur >=50 then
Output (bonus)
Else
Output (bonus)
End if
Else
Output (Pesan Error)
End.
e. Soal 5 Tarif Iklan
Deskripsi
hari : String
baris : Double
Implementasi
If hari = minggu Or hari = senin Or hari = selasa Or hari = rabu Or hari = kamis Or hari = jumat then
Output (baris * 33000)
Else if hari = sabtu then
Output (baris * 40000)
Else
Output (Pesan Error)
End.
f. Soal 6 Harga Tiket
Deskripsi
hari, jenis : String
tiket : Integer
Implementasi
If hari = senin Or hari = selasa Or hari = rabu Or hari = kamis then
If jenis = tidak then
Output (tiket*15000)
Else
Output (tiket*35000)
Else if hari = jumat Or hari = sabtu Or hari = minggu
If jenis = tidak then
Output (tiket*35000)
Else
Output (tiket*35000)
Else
Output (Pesan Error)
End.
g. Soal 7 Diskon Belanja
Deskripsi
total, diskon, bayar : Double
Implementasi
if total < 150000 then
diskon = total * 0%
bayar = total - diskon
Output (diskon)
Output (bayar)
Else if total < 275000 then
diskon = total * 10%
bayar = total - diskon
Output (diskon)
Output (bayar)
Else if total < 300000 then
diskon = total * 15%
bayar = total - diskon
Output (diskon)
Output (bayar)
Else if total < 400000 then
diskon = total * 20%
bayar  total - diskon
Output (diskon)
Output (bayar)
Else
diskon = total * 25%
bayar = total - diskon
Output (diskon)
Output (bayar)
End.
h. Soal 8 Nilai Huruf
Deskripsi
Nama : String
tugas1,tugas2,tugas3,UTS,UAS, rata2, total : Double
Implementasi
rata2 = (tugas1+tugas2+tugas3)/3;
total = (rata2*(30%))+(UTS*(30%))+(UAS*(40%));
if total > 0 And total <= 40 then
Output (total)
Output (“E”)
else if total > 40 And total <= 55
Output (total)
Output (“D”)
else if total > 55 And total <= 60
Output (total)
Output (“C”)
else if total > 60 And total <= 65
Output (total)
Output (“BC”)
else if total > 65 And total <= 70
Output (total)
Output (“B”)
else if total > 70 And total <= 80
Output (total)
Output (“AB”)
else if total > 80 And total <= 100
Output (total)
Output (“A”)
End.
i. Soal 9 Tarif PDAM
Deskripsi
Pemakaian : Double
Implementasi
If pemakaian <= 0 then
Output ( pemakaian*0 )
Else if pemakaian <= 50 then
Output ( pemakaian*200)
Else if pemakain <=150 then
Output ((50*200)+((pemakaian - 100) * 500))
Else if pemakaian <= 300 then
Output ((50 * 200) + (100 * 500) + ((pemakaian - 150) * 1000))
Else
Output ((50 * 200) + (100 * 500) + (150 * 1000) + ((pemakaian - 300) * 1500))
End.
j. Soal 10 Cash Back
Deskripsi
pemakaian1=  0 : Integer
pemakaian2 = 0 : Integer
pemakaian3 = 0 : Integer
pemakaian4 = 0 : Integer
cash_back_total= 0 : Integer
jml_pemakaian : Integer
Implementasi
pemakaian11000000
if jml_pemakaian<=1000000 then
pemakaian1 = jml_pemakaian
Else if jml_pemakaian > 1000000 And jml_pemakaian <= 10000000 then
pemakaian1  =10000000
pemakaian2 = jml_pemakaian – 1000000
Else if jml_pemakaian > 10000000 And jml_pemakaian <= 25000000 then
pemakaian2 = 10000000
pemakaian3 = jml_pemakaian-25000000
Else if jml_pemakaian > 25000000 then
pemakaian2  =10000000
pemakaian3 =  25000000
pemakaian4  =j ml_pemakaian – 25000000
cash_back_total=(pemakaian1*5%)+(pemakaian2*6%)+(pemakaian3*7%)+(pemakaian4*8%)
Output (jml_pemakaian , cash_back_total)

E.     REFERENSI
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/
Modul Pemrograman Berbasis Obyek :
JENI-Intro1-Bab01-Pengenalan Pemrograman Komputer.pdf
JENI-Intro1-Bab02-Pengenalan Bahasa Java.pdf
JENI-Intro1-Bab03-Mengenali Lingkup Pemrograman Anda.pdf
JENI-Intro1-Bab04-Dasar-Dasar Pemrograman.pdf
JENI-Intro1-Bab05-Mendapatkan Input dari Keyboard.pdf
JENI-Intro1-Bab06-Struktur Kontrol.pdf