• Tidak ada hasil yang ditemukan

Referensi Bahasa Pemrograman Java

N/A
N/A
Protected

Academic year: 2021

Membagikan "Referensi Bahasa Pemrograman Java"

Copied!
9
0
0

Teks penuh

(1)

Referensi Bahasa Pemrograman Java

Tipe Data Primitif

Type Bits Bytes Minimum Range Maximum Range

byte 8 1 -128 or -27 127 or 27-1

short 16 2 -32,768 or -215 32,767 or 215-1

int 32 4 -2,147,483,648 or -231 2,147,483,647 or 231-1

long 64 8 -263 263-1

float 32 4 -3.4E38 3.4E38

double 64 8 -1.7E308 1.7E308

char 16 2 n/a n/a

boolean 8 1 n/a n/a

Operator Aritmatika

Operator Name # Operands Description

+ Addition 2 Add two operands

- Subtraction 2 Subtract the right operand from the left * Multiplication 2 Multiplies the right operand and left operand / Division 2 Divides the right operand into the left operand % Modulus 2 Returns the value that is left over after dividing the

right operand into the left operand ++ Increment 1 Adds 1 to the operand (x = x + 1) -- Decrement 1 Subtracts 1 from the operand (x = x -1)

+ Positive Sign 1 Promotes byte, short, and char types to the int type - Negative Sign 1 Changes a positive value to negative, and vice versa

Karakter Khusus

Sequence Character \n New line \t Tab \r Return \” Quotation Mark \\ Backslash

(2)

Assignment Operators

Operator Name Description

= Assignment Assigns a new value to the variable

+= Addition Adds the operand to the starting variable value of the variable and assigns the result to the variable

-= Subtraction Subtracts the operand from the starting value of the variable and assigns the result to the variable

*= Multiplication Multiplies the operand by the starting value of the variable and assigns the result to the variable

/= Division Divides the operand by the starting value of the variable and assigns the result to the variable

%= Modulus Derives the value that is left over after dividing the right operand by the value in the variable, and then assigns this value to the variable

Ekspresi Boolean

Operator Name Description

== Equality Returns a true value if both operands are equals

!= Inequality Returns a true value if the left and right operands are not equal

> Greater Than Returns a true value if the left operand is greater than the right operand

< Less Than Return a true value if the left operand is less than the right operand

>= Greater Than Or Equal Returns a true value if the left operand is greater than or equal to the right operand

<= Less Than or Equal 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 a && b true if both a and b are true

|| OR a || b true if either a or b (or both) is true

^ XOR a ^ b true if only a or b is true

! NOT !a 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 +

(3)

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() Reads a String value from the user

nextInt() Reads an integer value from the user

nextDouble() Reads a double value from the user

(4)

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; }

(5)

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

(6)

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); }

(7)

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

(8)

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 }

(9)

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 }

Referensi

Dokumen terkait

Java dapat diigunakan untuk membuat sesuatu program sebagaimamna Anda membuatnya dengan bahasa seperti Pascal atau C++2. Yang lebih manarik, java juga mendukung

Penulisan tugas akhir ini bertujuan untuk membuat suatu program bantu untuk mempermudah dalam perancangan sebuah fondasi telapak dengan menggunakan bahasa pemrograman Java..

program input/output yang akan digunakan adalah class BufferedReader, maka. dibutuhkan class InputStreamReader untuk mendukung kinerja

Java adalah bahasa pemrograman berorientasi objek yang.. dikembangkan oleh Sun Microsystems sejak

Selain itu juga ada cara untuk mengimputkan data dari console dengan memanfaatkan kelas yang kita buat sendiri dimana kelas ini. nantinya akan diwariskan pada

public class Pertama adalah nama kelas yang kita buat (dalam java setiap membuat program berarti membuat sebuah kelas). public static void main(String args[]) adalah permulaan

JRE merupakan JAVA Runtime Environtment. JRE merupakan perangkat lunak yang digunakan untuk menjalankan program / aplikasi yang berbasis Java. Apabila kode - kode Java

Eclipse adalah IDE (Integrated Development Environment) yang sangat populer untuk Java dan C++, dengan menggunakan Eclipse pengembangan aplikasi akan lebih mudah dan