Download Referensi Bahasa Pemrograman Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Referensi Bahasa Pemrograman Java
Tipe Data Primitif
Type
Bits
Bytes
Minimum Range
Maximum Range
byte
short
int
long
float
double
char
boolean
8
16
32
64
32
64
16
8
1
2
4
8
4
8
2
1
-128 or -27
-32,768 or -215
-2,147,483,648 or -231
-263
-3.4E38
-1.7E308
n/a
n/a
127 or 27-1
32,767 or 215-1
2,147,483,647 or 231-1
263-1
3.4E38
1.7E308
n/a
n/a
Operator Aritmatika
Operator
Name
# Operands
Description
+
*
/
%
Addition
Subtraction
Multiplication
Division
Modulus
2
2
2
2
2
++
-+
-
Increment
Decrement
Positive Sign
Negative Sign
1
1
1
1
Add two operands
Subtract the right operand from the left
Multiplies the right operand and left operand
Divides the right operand into the left operand
Returns the value that is left over after dividing the
right operand into the left operand
Adds 1 to the operand (x = x + 1)
Subtracts 1 from the operand (x = x -1)
Promotes byte, short, and char types to the int type
Changes a positive value to negative, and vice versa
Karakter Khusus
Sequence
Character
\n
\t
\r
\”
\\
New line
Tab
Return
Quotation Mark
Backslash
Assignment Operators
Operator
Name
Description
=
+=
Assignment
Addition
-=
Subtraction
*=
Multiplication
/=
Division
%=
Modulus
Assigns a new value to the variable
Adds the operand to the starting variable value of the variable and
assigns the result to the variable
Subtracts the operand from the starting value of the variable and
assigns the result to the variable
Multiplies the operand by the starting value of the variable and
assigns the result to the variable
Divides the operand by the starting value of the variable and
assigns the result to the variable
Derives the value that is left over after dividing the right operand
by the value in the variable, and then assigns this value to the
variable
Ekspresi Boolean
Operator
Name
Description
==
!=
>
Equality
Inequality
Greater Than
<
Less Than
>=
Greater Than Or Equal
<=
Less Than or Equal
Returns a true value if both operands are equals
Returns a true value if the left and right operands are not equal
Returns a true value if the left operand is greater than the right
operand
Return a true value if the left operand is less than the right
operand
Returns a true value if the left operand is greater than or equal to
the right operand
Return a true value if the left operand is less than or equal to the
right operand
Operator AND dan OR
Operator
Name
Example
Description
&&
||
^
!
AND
OR
XOR
NOT
a && b
a || b
a^b
!a
true if both a and b are true
true if either a or b (or both) is true
true if only a or b is true
true if a is not true
String
 String bukan merupakan tipe data primitif melainkan tipe data reference
 Contoh: String message1 = "Invalid data entry";
 Untuk menyambung (concat) dua/lebih string, gunakan operator +
 Untuk membandingkan 2 buah String, kita harus menggunakan method “equals” atau
“equalgnoreCase” yang dimiliki oleh kelas String.
Variabel & Assignment
 Sintaks: tipeData namaVariabel
 Contoh:
 int counter = 1;
 boolean valid = false;
 char letter = ‘A’;
 char letter = 65;
 double distance = 3.65e+9;
Method print, println,dan printf
 print  posisi akhir kursor berada di garis yang sama
o
Contoh: System.out.print ("Hello World");
 println  posisi akhir kursor berada di garis yang baru (seolah menekan enter)
o
Contoh: System.out.println("Hello World");
 printf  print dalam bentuk format tertentu (f = formatted)
o
Contoh: System.out.printf("%s\n %s\n", "Hello", "World");
Using Console for Input & Output
 Dengan java versi 5, cara paling mudah untuk mendapatkan input dari console adalah
dengan menggunakan Scanner class
 Untuk menampilkan output ke console adalah menggunakan method (fungsi)
System.out.println
 Sebelum menggunakan Scanner class, kita harus melakukan proses import sbb:
import java.util.Scanner;
 Untuk membaca input dari console, kita buat objek scanner dengan cara menuliskannya sbb:
Scanner sc = new Scanner(System.in);
 Ada 4 buah methods dari objek Scanner (yaitu sc) yang dapat kita gunakan sesuai
kebutuhan:
Method
Description
next() or nextLine()
nextInt()
nextDouble()
nextBoolean()
Reads a String value from the user
Reads an integer value from the user
Reads a double value from the user
Reads a boolean value from the user
Struktur Kontrol Selection
Java memiliki 5 conditional statements yaitu: if, else, switch, case, dan break.
1. IF
2. IF-ELSE
3. SWITCH-CASE
switch (expr) { //note: expr hanya boleh berupa int atau char
case value1:
statement_1a;
statement_1b;
break;
case value2:
statement_2;
break;
default:
statement_da;
statement_db;
break;
}
Struktur Kontrol Loop
1. While Loop
while (true){
// statements
}
2. Do-While Loop
do {
//statements (body)
}
while (expression);
3. For Loop
Note:

Init: statement untuk menginisialisasi variabel loop, dieksekusi sekali

Cont: Ekspresi Boolean untuk keberlanjutan loop, dieksekusi sebelum pengulangan

Adj: statement untuk meng-adjust variabel loop, dieksekusi setelah pengulangan
Array
Array adalah variabel yang yang dikelompokkan bersama dalam suatu nama.
Ada 4 Tahap Manipulasi Array:
1. Array declaration
2. Array creation
3. Array initialization
4. Array processing
Contoh Deklarasi Array:
 String[] students;
// An array of String variables
 int[] values;
// An array of integer variables
 boolean[] truthTable; // An array of boolean variables
 char[] grades;
// An array of character variables
Contoh Pembuatan Array:
 String[] names = new String[10];
 Int[] numbers = new int[20];
Contoh Inisialisasi Array:
 Cara 1: assign satu per satu:
String[] days = new String[7];
days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";
 Cara 2: shorthand way menggunakan { }:
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday" };
Contoh Pemrosesan & Menampilkan Isi Array Menggunakan FOR-LOOP:
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday","Friday", "Saturday" };
for (int i = 0; i < days.length; i++{
System.out.println(days[i]);
}
Contoh Pemrosesan & Menampilkan Array Menggunakan: Enhanced FOR-LOOP (FOREACH):
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday","Friday", "Saturday" };
for (String dayElement: days){
System.out.println(dayElement);
}
Exception Handling
 Exceptional adalah kesalahan (error) yang disebabkan oleh situasi yang TIDAK DAPAT
DIGARANSI 100% OKE ketika program dijalankan (saat runtime)
 An exception is an object that’s created when an error occurs in a Java program and Java can’t
automatically fix the error.
 The exception object contains information about the type of error that occurred.
 Java Exception Hierarchy:
Handling Exception: Try-Catch
We catch an exception by using a try-catch statement, which has this general form:
try {
// statements that can throw exceptions
}
catch (exception-type identifier) {
// statements executed when exception is thrown
}
Contoh Penanganan Exception pada kasus “Divide-by-Zero”:
public class DivideByZero {
public static void main(String[] args){
int a = 5;
int b = 0;
// you know this won’t work
try {
int c = a / b; // but you try it anyway
}
catch (ArithmeticException e){
System.out.println("Oops, you can’t divide by zero.");
}
}
}
Catching All Exceptions
If we have some code that might throw several different types of exceptions, and we want to
provide specific processing for some but general processing for all the others, we can code the try
statement as following:
try {
// statements that might throw several types of exceptions
}
catch (InputMismatchException e) {
// statements that process InputMismatchException
}
catch (IOException e) {
// statements that process IOException
}
catch (Exception e) {
// statements that process all other exception types
}
Finally
 A finally block is a block that appears after all of the catch blocks for a statement.
 It’s executed whether or not any exceptions are thrown by the try block or caught by any catch
blocks.
 The basic framework for a try statement with a finally block is this:
try {
// statements that can throw exceptions
}
catch (exception-type identifier){
// statements executed when exception is thrown
}
finally{
// statements that are executed
// whether or not exceptions occur
}
© Niko Ibrahim, S.Kom, MIT