E-Book: Pemrograman Java
Dari Dasar hingga Mahir
Da6ar Isi
1. Pengenalan Java
2. Instalasi dan Persiapan Environment
3. Sintaks Dasar Java
4. Variabel dan Tipe Data
5. Operator dan Ekspresi
6. Struktur Kontrol
7. Array dan CollecIon
8. Method dan FuncIon
9. Object-Oriented Programming
10. ExcepIon Handling
11. File I/O dan Stream
12. Generic Programming
13. MulI-threading
14. Database ConnecIvity
15. Best PracIces
16. Project Akhir
1. Pengenalan Java
Apa itu Java?
Java adalah bahasa pemrograman berorientasi objek yang dikembangkan oleh Sun
Microsystems (sekarang Oracle) pada tahun 1995. Java dirancang dengan filosofi "Write
Once, Run Anywhere" (WORA), yang berarI kode Java dapat berjalan di berbagai pla_orm
tanpa perlu diubah.
KarakterisAk Utama Java:
• PlaCorm Independent: Kode Java dikompilasi menjadi bytecode yang dapat berjalan
di Java Virtual Machine (JVM)
• Object-Oriented: Mendukung konsep OOP seperI inheritance, encapsulaIon, dan
polymorphism
• Robust: Memiliki sistem penanganan error yang kuat dan garbage collecIon
otomaIs
• Secure: Memiliki fitur keamanan built-in
• MulA-threaded: Mendukung pemrograman concurrent
Kegunaan Java:
• Aplikasi Desktop (Swing, JavaFX)
• Aplikasi Web (Spring, JSF, Servlets)
• Aplikasi Mobile (Android)
• Enterprise ApplicaIons
• Big Data Processing (Apache Spark, Hadoop)
• Microservices
2. Instalasi dan Persiapan Environment
Instalasi JDK (Java Development Kit)
1. Download JDK:
o Kunjungi website Oracle atau OpenJDK
o Pilih versi terbaru (Java 17 atau 21 direkomendasikan)
o Download sesuai dengan sistem operasi Anda
2. Instalasi:
o Jalankan installer dan ikuI petunjuk
o PasIkan JDK terinstal di direktori yang mudah diakses
3. SeOng PATH Environment:
4. # Windows
5. set PATH=%PATH%;C:\Program Files\Java\jdk-17\bin
6.
7. # Linux/Mac
8. export PATH=$PATH:/usr/lib/jvm/java-17-openjdk/bin
IDE (Integrated Development Environment)
Pilihan IDE populer untuk Java:
• Eclipse: GraIs dan open-source
• IntelliJ IDEA: Powerful dengan versi Community graIs
• NetBeans: Dari Apache, graIs dan user-friendly
• Visual Studio Code: Lightweight dengan extension Java
Verifikasi Instalasi
# Cek versi Java
java -version
# Cek versi compiler
javac -version
3. Sintaks Dasar Java
Struktur Program Java
// Nama file: [Link]
public class HelloWorld {
public staIc void main(String[] args) {
[Link]("Hello, World!");
}
}
Komponen Dasar:
1. Package DeclaraAon (opsional):
2. package [Link];
3. Import Statements:
4. import [Link];
5. import [Link].*;
6. Class DeclaraAon:
7. public class ClassName {
8. // class body
9. }
10. Main Method:
11. public staIc void main(String[] args) {
12. // program entry point
13. }
Aturan Penamaan:
• Class: PascalCase (ContohClass)
• Method: camelCase (contohMethod)
• Variable: camelCase (contohVariable)
• Constant: UPPER_CASE (CONTOH_KONSTANTA)
Komentar:
// Komentar satu baris
/*
Komentar
mulI baris
*/
/**
* Javadoc comment
* @param parameter deskripsi parameter
* @return deskripsi return value
*/
4. Variabel dan Tipe Data
Tipe Data PrimiAf
// Integer types
byte byteVar = 100; // 8-bit: -128 to 127
short shortVar = 1000; // 16-bit: -32,768 to 32,767
int intVar = 100000; // 32-bit: -2^31 to 2^31-1
long longVar = 100000L; // 64-bit: -2^63 to 2^63-1
// FloaIng point types
float floatVar = 10.5f; // 32-bit floaIng point
double doubleVar = 10.5; // 64-bit floaIng point
// Character and Boolean
char charVar = 'A'; // 16-bit Unicode character
boolean boolVar = true; // true or false
Tipe Data Reference
// String
String stringVar = "Hello Java";
// Arrays
int[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = new String[10];
// Objects
Scanner scanner = new Scanner([Link]);
ArrayList<String> list = new ArrayList<>();
Deklarasi dan Inisialisasi
// Deklarasi
int number;
// Inisialisasi
number = 10;
// Deklarasi dan inisialisasi sekaligus
int anotherNumber = 20;
// MulIple declaraIon
int a, b, c;
int x = 1, y = 2, z = 3;
Konstanta
// Final variable (konstanta)
final int MAX_SIZE = 100;
final String APP_NAME = "MyApplicaIon";
// StaIc final (class constant)
public staIc final double PI = 3.14159;
Type CasAng
// Implicit casIng (widening)
int intValue = 10;
double doubleValue = intValue; // int to double
// Explicit casIng (narrowing)
double doubleVal = 10.5;
int intVal = (int) doubleVal; // double to int (data loss possible)
// String conversion
int number = 123;
String stringNumber = [Link](number);
int convertedBack = [Link](stringNumber);
5. Operator dan Ekspresi
Operator AritmaAka
int a = 10, b = 3;
int penjumlahan = a + b; // 13
int pengurangan = a - b; // 7
int perkalian = a * b; // 30
int pembagian = a / b; // 3 (integer division)
int modulus = a % b; // 1 (sisa bagi)
// Increment dan Decrement
a++; // post-increment: gunakan nilai a, lalu tambah 1
++a; // pre-increment: tambah 1, lalu gunakan nilai a
b--; // post-decrement
--b; // pre-decrement
Operator Assignment
int x = 10;
x += 5; // x = x + 5 (15)
x -= 3; // x = x - 3 (12)
x *= 2; // x = x * 2 (24)
x /= 4; // x = x / 4 (6)
x %= 3; // x = x % 3 (0)
Operator Perbandingan
int a = 10, b = 5;
boolean equal = (a == b); // false
boolean notEqual = (a != b); // true
boolean greater = (a > b); // true
boolean greaterEqual = (a >= b); // true
boolean less = (a < b); // false
boolean lessEqual = (a <= b); // false
Operator Logika
boolean x = true, y = false;
boolean and = x && y; // false (logical AND)
boolean or = x || y; // true (logical OR)
boolean not = !x; // false (logical NOT)
// Short-circuit evaluaIon
boolean result = (5 > 3) || (10 / 0 == 0); // true, Idak error
Operator Bitwise
int a = 5; // 101 in binary
int b = 3; // 011 in binary
int bitwiseAnd = a & b; // 1 (001)
int bitwiseOr = a | b; // 7 (111)
int bitwiseXor = a ^ b; // 6 (110)
int bitwiseNot = ~a; // -6 (two's complement)
int le€Shi€ = a << 1; // 10 (1010)
int rightShi€ = a >> 1; // 2 (010)
Operator Ternary
int a = 10, b = 5;
int max = (a > b) ? a : b; // max = 10
String result = (a % 2 == 0) ? "genap" : "ganjil";
6. Struktur Kontrol
If-Else Statement
// If statement sederhana
int nilai = 85;
if (nilai >= 70) {
[Link]("Lulus");
}
// If-else
if (nilai >= 70) {
[Link]("Lulus");
} else {
[Link]("Tidak Lulus");
}
// If-else if-else
if (nilai >= 90) {
[Link]("Grade A");
} else if (nilai >= 80) {
[Link]("Grade B");
} else if (nilai >= 70) {
[Link]("Grade C");
} else {
[Link]("Grade D");
}
Switch Statement
// Switch dengan break
int hari = 3;
String namaHari;
switch (hari) {
case 1:
namaHari = "Senin";
break;
case 2:
namaHari = "Selasa";
break;
case 3:
namaHari = "Rabu";
break;
default:
namaHari = "Hari Idak valid";
break;
}
// Switch expression (Java 12+)
String namaHariModern = switch (hari) {
case 1 -> "Senin";
case 2 -> "Selasa";
case 3 -> "Rabu";
default -> "Hari Idak valid";
};
For Loop
// TradiIonal for loop
for (int i = 0; i < 10; i++) {
[Link]("Iterasi ke-" + i);
}
// Enhanced for loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
[Link](number);
}
// Nested for loop
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
[Link](i + "," + j + " ");
}
[Link]();
}
While Loop
// While loop
int i = 0;
while (i < 5) {
[Link]("i = " + i);
i++;
}
// Do-while loop
int j = 0;
do {
[Link]("j = " + j);
j++;
} while (j < 5);
Break dan ConAnue
// Break statement
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Keluar dari loop
}
[Link](i);
}
// ConInue statement
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
conInue; // Skip iterasi ini
}
[Link](i); // Hanya print angka ganjil
}
7. Array dan CollecAon
Array
// Deklarasi dan inisialisasi array
int[] numbers = new int[5]; // Array dengan 5 elemen
int[] values = {1, 2, 3, 4, 5}; // Array dengan nilai langsung
// Mengakses elemen array
numbers[0] = 10;
numbers[1] = 20;
int firstValue = values[0];
// Panjang array
int length = [Link];
// MulI-dimensional array
int[][] matrix = new int[3][4]; // 3 baris, 4 kolom
int[][] values2D = {{1, 2}, {3, 4}, {5, 6}};
// Mengiterasi array
for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}
// Enhanced for loop
for (int value : values) {
[Link](value);
}
ArrayList
import [Link];
// Membuat ArrayList
ArrayList<String> names = new ArrayList<>();
// Menambah elemen
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
// Mengakses elemen
String firstName = [Link](0);
// Mengubah elemen
[Link](1, "Robert");
// Menghapus elemen
[Link](2); // Hapus berdasarkan index
[Link]("Alice"); // Hapus berdasarkan nilai
// Ukuran ArrayList
int size = [Link]();
// Iterasi
for (String name : names) {
[Link](name);
}
HashMap
import [Link];
// Membuat HashMap
HashMap<String, Integer> ages = new HashMap<>();
// Menambah key-value pair
[Link]("Alice", 25);
[Link]("Bob", 30);
[Link]("Charlie", 35);
// Mengakses nilai
Integer aliceAge = [Link]("Alice");
// Cek apakah key ada
if ([Link]("Alice")) {
[Link]("Alice's age: " + [Link]("Alice"));
}
// Iterasi
for (String name : [Link]()) {
[Link](name + ": " + [Link](name));
}
HashSet
import [Link];
// Membuat HashSet
HashSet<String> uniqueNames = new HashSet<>();
// Menambah elemen
[Link]("Alice");
[Link]("Bob");
[Link]("Alice"); // Duplikat, Idak akan ditambahkan
// Cek apakah elemen ada
if ([Link]("Alice")) {
[Link]("Alice is in the set");
}
// Ukuran set
int size = [Link](); // 2
8. Method dan FuncAon
Deklarasi Method
public class Calculator {
// Method sederhana tanpa parameter dan return value
public void sayHello() {
[Link]("Hello!");
}
// Method dengan parameter
public void greet(String name) {
[Link]("Hello, " + name + "!");
}
// Method dengan return value
public int add(int a, int b) {
return a + b;
}
// Method dengan mulIple parameters
public double calculateArea(double length, double width) {
return length * width;
}
// Method overloading
public int mulIply(int a, int b) {
return a * b;
}
public double mulIply(double a, double b) {
return a * b;
}
public int mulIply(int a, int b, int c) {
return a * b * c;
}
}
StaAc Method
public class MathUIls {
// StaIc method - dapat dipanggil tanpa membuat instance
public staIc int max(int a, int b) {
return (a > b) ? a : b;
}
public staIc double circleArea(double radius) {
return [Link] * radius * radius;
}
}
// Penggunaan staIc method
int maximum = [Link](10, 20);
double area = [Link](5.0);
Variable Arguments (Varargs)
public class VarargsExample {
// Method dengan varargs
public staIc int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public staIc void main(String[] args) {
int result1 = sum(1, 2, 3); // 6
int result2 = sum(1, 2, 3, 4, 5); // 15
int result3 = sum(); // 0
}
}
Recursion
public class RecursionExample {
// Factorial menggunakan recursion
public staIc long factorial(int n) {
if (n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive case
}
// Fibonacci menggunakan recursion
public staIc int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
public staIc void main(String[] args) {
[Link]("5! = " + factorial(5)); // 120
[Link]("Fib(7) = " + fibonacci(7)); // 13
}
}
9. Object-Oriented Programming
Class dan Object
// Definisi class
public class Person {
// Instance variables (a‚ributes)
private String name;
private int age;
private String email;
// Constructor default
public Person() {
[Link] = "";
[Link] = 0;
[Link] = "";
}
// Constructor dengan parameter
public Person(String name, int age, String email) {
[Link] = name;
[Link] = age;
[Link] = email;
}
// Ge‚er methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
// Se‚er methods
public void setName(String name) {
[Link] = name;
}
public void setAge(int age) {
if (age >= 0) {
[Link] = age;
}
}
public void setEmail(String email) {
[Link] = email;
}
// Instance method
public void introduce() {
[Link]("Hi, I'm " + name + ", " + age + " years old.");
}
// Override toString method
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + ", email='" + email + "'}";
}
}
// Penggunaan class
public class PersonDemo {
public staIc void main(String[] args) {
// Membuat object
Person person1 = new Person();
Person person2 = new Person("Alice", 25, "alice@[Link]");
// Menggunakan se‚er
[Link]("Bob");
[Link](30);
[Link]("bob@[Link]");
// Menggunakan method
[Link]();
[Link]();
// Menggunakan ge‚er
[Link]([Link]() + " is " + [Link]() + " years old");
}
}
Inheritance (Pewarisan)
// Parent class (superclass)
public class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
[Link] = name;
[Link] = age;
}
public void eat() {
[Link](name + " is eaIng");
}
public void sleep() {
[Link](name + " is sleeping");
}
public void makeSound() {
[Link](name + " makes a sound");
}
}
// Child class (subclass)
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age); // Memanggil constructor parent
[Link] = breed;
}
// Method overriding
@Override
public void makeSound() {
[Link](name + " barks: Woof! Woof!");
}
// Method khusus untuk Dog
public void wagTail() {
[Link](name + " is wagging tail");
}
public String getBreed() {
return breed;
}
}
public class Cat extends Animal {
private boolean isIndoor;
public Cat(String name, int age, boolean isIndoor) {
super(name, age);
[Link] = isIndoor;
}
@Override
public void makeSound() {
[Link](name + " meows: Meow! Meow!");
}
public void climb() {
[Link](name + " is climbing");
}
}
Polymorphism
public class PolymorphismDemo {
public staIc void main(String[] args) {
// Polymorphism - satu reference variable, berbagai object type
Animal[] animals = {
new Dog("Buddy", 3, "Golden Retriever"),
new Cat("Whiskers", 2, true),
new Dog("Max", 5, "German Shepherd")
};
// Method yang sama dipanggil, tapi behavior berbeda
for (Animal animal : animals) {
[Link](); // Polymorphic method call
[Link]();
// DowncasIng dengan instanceof
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
[Link]();
[Link]("Breed: " + [Link]());
} else if (animal instanceof Cat) {
Cat cat = (Cat) animal;
[Link]();
}
[Link]("---");
}
}
}
Abstract Class dan Interface
// Abstract class
public abstract class Shape {
protected String color;
public Shape(String color) {
[Link] = color;
}
// Abstract method - harus diimplementasi oleh subclass
public abstract double calculateArea();
public abstract double calculatePerimeter();
// Concrete method
public void displayInfo() {
[Link]("This is a " + color + " shape");
[Link]("Area: " + calculateArea());
[Link]("Perimeter: " + calculatePerimeter());
}
}
// Interface
public interface Drawable {
void draw();
void erase();
// Default method (Java 8+)
default void highlight() {
[Link]("HighlighIng the shape");
}
// StaIc method (Java 8+)
staIc void printDrawingInfo() {
[Link]("Drawing shapes...");
}
}
// Implementasi abstract class dan interface
public class Circle extends Shape implements Drawable {
private double radius;
public Circle(String color, double radius) {
super(color);
[Link] = radius;
}
@Override
public double calculateArea() {
return [Link] * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * [Link] * radius;
}
@Override
public void draw() {
[Link]("Drawing a " + color + " circle with radius " + radius);
}
@Override
public void erase() {
[Link]("Erasing the circle");
}
}
public class Rectangle extends Shape implements Drawable {
private double length;
private double width;
public Rectangle(String color, double length, double width) {
super(color);
[Link] = length;
[Link] = width;
}
@Override
public double calculateArea() {
return length * width;
}
@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
@Override
public void draw() {
[Link]("Drawing a " + color + " rectangle " + length + "x" + width);
}
@Override
public void erase() {
[Link]("Erasing the rectangle");
}
}
10. ExcepAon Handling
Try-Catch-Finally
import [Link];
import [Link];
import [Link];
public class ExcepIonHandlingExample {
public staIc void basicTryCatch() {
try {
int result = 10 / 0; // ArithmeIcExcepIon
[Link]("Result: " + result);
} catch (ArithmeIcExcepIon e) {
[Link]("Error: Division by zero!");
[Link]("ExcepIon message: " + [Link]());
}
[Link]("Program conInues...");
}
public staIc void mulIpleCatch() {
Scanner scanner = new Scanner([Link]);
try {
[Link]("Enter array size: ");
int size = [Link]([Link]());
int[] array = new int[size];
[Link]("Enter index to access: ");
int index = [Link]([Link]());
[Link]("Value at index " + index + ": " + array[index]);
} catch (NumberFormatExcepIon e) {
[Link]("Invalid number format!");
} catch (NegaIveArraySizeExcepIon e) {
[Link]("Array size cannot be negaIve!");
} catch (ArrayIndexOutOfBoundsExcepIon e) {
[Link]("Array index out of bounds!");
} catch (ExcepIon e) {
[Link]("Unexpected error: " + [Link]());
} finally {
// Block ini selalu dieksekusi
[Link]("Cleanup operaIons...");
[Link]();
}
}
public staIc void tryWithResources() {
// Try-with-resources (Java 7+)
try (Scanner fileScanner = new Scanner(new FileReader("[Link]"))) {
while (fi[Link]()) {
[Link](fi[Link]());
}
} catch (IOExcepIon e) {
[Link]("File reading error: " + [Link]());
}
// Scanner otomaIs di-close
}
}
Custom ExcepAon
// Custom excepIon class
public class InsufficientFundsExcepIon extends ExcepIon {
private double amount;
public InsufficientFundsExcepIon(double amount) {
super("Insufficient funds. A‚empted to withdraw: $" + amount);
[Link] = amount;
}
public double getAmount() {
return amount;
}
}
// Class yang menggunakan custom excepIon
public class BankAccount {
private double balance;
private String accountNumber;
public BankAccount(String accountNumber, double iniIalBalance) {
[Link] = accountNumber;
[Link] = iniIalBalance;
}
public void withdraw(double amount) throws InsufficientFundsExcepIon {
if (amount > balance) {
throw new InsufficientFundsExcepIon(amount);
}
balance -= amount;
[Link]("Withdrawn: $" + amount + ". New balance: $" + balance);
}
public void deposit(double amount) {
balance += amount;
[Link]("Deposited: $" + amount + ". New balance: $" + balance);
}
public double getBalance() {
return balance;
}
}
// Penggunaan custom excepIon
public class BankDemo {
public staIc void main(String[] args) {
BankAccount account = new BankAccount("12345", 1000.0);
try {
[Link](500); // OK
[Link](600); // Akan throw excepIon
} catch (InsufficientFundsExcepIon e) {
[Link]("TransacIon failed: " + [Link]());
[Link]("Available balance: $" + [Link]());
}
}
}
Checked vs Unchecked ExcepAons
import [Link];
import [Link];
public class ExcepIonTypes {
// Checked ExcepIon - harus di-handle atau di-declare
public staIc void readFile(String filename) throws IOExcepIon {
FileReader file = new FileReader(filename); // IOExcepIon (checked)
// ... file processing
fi[Link]();
}
// Unchecked ExcepIon - Idak wajib di-handle
public staIc void uncheckedExamples() {
// RunImeExcepIon dan subclassnya adalah unchecked
try {
// NullPointerExcepIon (unchecked)
String str = null;
int length = [Link]();
// ArrayIndexOutOfBoundsExcepIon (unchecked)
int[] array = {1, 2, 3};
int value = array[5];
// ArithmeIcExcepIon (unchecked)
int result = 10 / 0;
} catch (RunImeExcepIon e) {
[Link]("RunIme excepIon caught: " + [Link]().getSimpleName());
}
}
public staIc void main(String[] args) {
// Checked excepIon harus di-handle
try {
readFile("[Link]");
} catch (IOExcepIon e) {
[Link]("File not found: " + [Link]());
}
// Unchecked excepIon boleh di-handle atau Idak
uncheckedExamples();
}
}
11. File I/O dan Stream
File Reading dan WriAng
import [Link].*;
import [Link].file.*;
import [Link];
public class FileIOExample {
// Membaca file dengan BufferedReader
public staIc void readWithBufferedReader(String filename) {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOExcepIon e) {
[Link]("Error reading file: " + [Link]());
}
}
// Menulis file dengan BufferedWriter
public staIc void writeWithBufferedWriter(String filename, String[] data) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
for (String line : data) {
[Link](line);
[Link]();
}
[Link]("File wri‚en successfully!");
} catch (IOExcepIon e) {
[Link]("Error wriIng file: " + [Link]());
}
}
// File I/O dengan Java NIO (Java 7+)
public staIc void nioFileOperaIons() {
Path path = [Link]("[Link]");
try {
// Menulis ke file
String content = "Hello, World!\nThis is line 2\nThis is line 3";
[Link](path, [Link]());
// Membaca seluruh file
String fileContent = new String([Link](path));
[Link]("File content:\n" + fileContent);
// Membaca file per baris
List<String> lines = [Link](path);
[Link]("\nReading line by line:");
for (int i = 0; i < [Link](); i++) {
[Link]("Line " + (i + 1) + ": " + [Link](i));
}
// Cek apakah file/directory ada
if ([Link](path)) {
[Link]("File exists");
[Link]("File size: " + [Link](path) + " bytes");
}
} catch (IOExcepIon e) {
[Link]("NIO operaIon failed: " + [Link]());
}
}
// Operasi directory
public staIc void directoryOperaIons() {
try {
// Membuat directory
Path dir = [Link]("testDir");
if () {
[Link](dir);
[Link]("Directory created: " + dir);
}
// List files dalam directory
[Link]([Link]("."))
.filter(Files::isRegularFile)
.forEach([Link]::println);
} catch (IOExcepIon e) {
[Link]("Directory operaIon failed: " + [Link]());
}
}
}
SerializaAon
import [Link].*;
// Class yang dapat diserialisasi
public class Student implements Serializable {
private staIc final long serialVersionUID = 1L;
private String name;
private int age;
private double gpa;
private transient String password; // Idak akan diserialisasi
public Student(String name, int age, double gpa, String password) {
[Link] = name;
[Link] = age;
[Link] = gpa;
[Link] = password;
}
// Ge‚ers dan toString
public String getName() { return name; }
public int getAge() { return age; }
public double getGpa() { return gpa; }
public String getPassword() { return password; }
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + ", gpa=" + gpa +
", password='" + password + "'}";
}
}
public class SerializaIonExample {
// Serialisasi object ke file
public staIc void serializeStudent(Student student, String filename) {
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
[Link](student);
[Link]("Student serialized successfully!");
} catch (IOExcepIon e) {
[Link]("SerializaIon failed: " + [Link]());
}
}
// Deserialisasi object dari file
public staIc Student deserializeStudent(String filename) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
Student student = (Student) [Link]();
[Link]("Student deserialized successfully!");
return student;
} catch (IOExcepIon | ClassNotFoundExcepIon e) {
[Link]("DeserializaIon failed: " + [Link]());
return null;
}
}
public staIc void main(String[] args) {
Student student = new Student("Alice", 20, 3.8, "secret123");
[Link]("Original: " + student);
// Serialize
serializeStudent(student, "[Link]");
// Deserialize
Student deserializedStudent = deserializeStudent("[Link]");
if (deserializedStudent != null) {
[Link]("Deserialized: " + deserializedStudent);
// PerhaIkan password menjadi null karena transient
}
}
}
12. Generic Programming
Basic Generics
// Generic class
public class Box<T> {
private T content;
public void setContent(T content) {
[Link] = content;
}
public T getContent() {
return content;
}
public boolean isEmpty() {
return content == null;
}
}
// Generic class dengan mulIple type parameters
public class Pair<T, U> {
private T first;
private U second;
public Pair(T first, U second) {
this.first = first;
[Link] = second;
}
public T getFirst() { return first; }
public U getSecond() { return second; }
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
// Penggunaan generic classes
public class GenericDemo {
public staIc void main(String[] args) {
// Box untuk Integer
Box<Integer> intBox = new Box<>();
[Link](42);
Integer intValue = [Link]();
// Box untuk String
Box<String> stringBox = new Box<>();
[Link]("Hello Generics");
String stringValue = [Link]();
// Pair dengan berbagai Ipe
Pair<String, Integer> nameAge = new Pair<>("Alice", 25);
Pair<Integer, Double> coordinates = new Pair<>(10, 20.5);
[Link]("Name-Age: " + nameAge);
[Link]("Coordinates: " + coordinates);
}
}
Generic Methods
public class GenericMethods {
// Generic method
public staIc <T> void swap(T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// Generic method dengan bounded type parameter
public staIc <T extends Comparable<T>> T findMax(T[] array) {
if ([Link] == 0) return null;
T max = array[0];
for (int i = 1; i < [Link]; i++) {
if (array[i].compareTo(max) > 0) {
max = array[i];
}
}
return max;
}
// Generic method dengan mulIple bounds
public staIc <T extends Comparable<T> & Cloneable> T cloneMax(T[] array) {
T max = findMax(array);
try {
return (T) [Link]();
} catch (CloneNotSupportedExcepIon e) {
return null;
}
}
public staIc void main(String[] args) {
Integer[] numbers = {3, 1, 4, 1, 5, 9, 2, 6};
String[] words = {"banana", "apple", "cherry", "date"};
[Link]("Before swap: " + [Link](numbers));
swap(numbers, 0, [Link] - 1);
[Link]("A€er swap: " + [Link](numbers));
Integer maxNumber = findMax(numbers);
String maxWord = findMax(words);
[Link]("Max number: " + maxNumber);
[Link]("Max word: " + maxWord);
}
}
Wildcards
import [Link].*;
public class WildcardExample {
// Upper bound wildcard (? extends T)
public staIc double calculateTotal(List<? extends Number> numbers) {
double total = 0.0;
for (Number num : numbers) {
total += [Link]();
}
return total;
}
// Lower bound wildcard (? super T)
public staIc void addNumbers(List<? super Integer> numbers) {
[Link](1);
[Link](2);
[Link](3);
}
// Unbounded wildcard (?)
public staIc int countElements(List<?> list) {
return [Link]();
}
public staIc void printList(List<?> list) {
for (Object item : list) {
[Link](item + " ");
}
[Link]();
}
public staIc void main(String[] args) {
List<Integer> integers = [Link](1, 2, 3, 4, 5);
List<Double> doubles = [Link](1.1, 2.2, 3.3);
List<String> strings = [Link]("a", "b", "c");
// Upper bound - dapat menerima List<Integer> dan List<Double>
[Link]("Total integers: " + calculateTotal(integers));
[Link]("Total doubles: " + calculateTotal(doubles));
// Lower bound
List<Number> numbers = new ArrayList<>();
addNumbers(numbers); // Menambah Integer ke List<Number>
// Unbounded
[Link]("Count integers: " + countElements(integers));
[Link]("Count strings: " + countElements(strings));
printList(integers);
printList(strings);
}
}
13. MulA-threading
Thread CreaAon
// Cara 1: Extend Thread class
class MyThread extends Thread {
private String threadName;
public MyThread(String name) {
[Link] = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](threadName + " - Count: " + i);
try {
[Link](1000); // Sleep 1 deIk
} catch (InterruptedExcepIon e) {
[Link](threadName + " interrupted");
}
}
[Link](threadName + " finished");
}
}
// Cara 2: Implement Runnable interface
class MyRunnable implements Runnable {
private String taskName;
public MyRunnable(String name) {
[Link] = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](taskName + " - IteraIon: " + i);
try {
[Link](800);
} catch (InterruptedExcepIon e) {
[Link](taskName + " interrupted");
}
}
[Link](taskName + " completed");
}
}
public class ThreadExample {
public staIc void main(String[] args) {
// Menggunakan Thread class
MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");
// Menggunakan Runnable interface
Thread thread3 = new Thread(new MyRunnable("Task-1"));
Thread thread4 = new Thread(new MyRunnable("Task-2"));
// Menggunakan lambda expression (Java 8+)
Thread thread5 = new Thread(() -> {
for (int i = 1; i <= 3; i++) {
[Link]("Lambda Thread - " + i);
try {
[Link](1500);
} catch (InterruptedExcepIon e) {
[Link]().interrupt();
}
}
});
// Start threads
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
// Wait for all threads to complete
try {
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
} catch (InterruptedExcepIon e) {
[Link]("Main thread interrupted");
}
[Link]("All threads completed");
}
}
SynchronizaAon
// Shared resource tanpa synchronizaIon - problem!
class UnsafeCounter {
private int count = 0;
public void increment() {
count++; // Not thread-safe!
}
public int getCount() {
return count;
}
}
// Thread-safe counter dengan synchronized
class SafeCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
// Menggunakan synchronized block
class BankAccount {
private double balance;
private final Object lock = new Object();
public BankAccount(double iniIalBalance) {
[Link] = iniIalBalance;
}
public void deposit(double amount) {
synchronized (lock) {
balance += amount;
[Link]("Deposited: " + amount + ", Balance: " + balance);
}
}
public void withdraw(double amount) {
synchronized (lock) {
if (balance >= amount) {
balance -= amount;
[Link]("Withdrawn: " + amount + ", Balance: " + balance);
} else {
[Link]("Insufficient funds");
}
}
}
public synchronized double getBalance() {
return balance;
}
}
public class SynchronizaIonExample {
public staIc void main(String[] args) throws InterruptedExcepIon {
SafeCounter counter = new SafeCounter();
// Buat mulIple threads yang increment counter
Thread[] threads = new Thread[10];
for (int i = 0; i < [Link]; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
[Link]();
}
});
}
// Start all threads
for (Thread thread : threads) {
[Link]();
}
// Wait for compleIon
for (Thread thread : threads) {
[Link]();
}
[Link]("Final count: " + [Link]()); // Should be 10000
// Bank account example
BankAccount account = new BankAccount(1000);
Thread depositor = new Thread(() -> {
for (int i = 0; i < 5; i++) {
[Link](100);
try { [Link](100); } catch (InterruptedExcepIon e) {}
}
});
Thread withdrawer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
[Link](150);
try { [Link](150); } catch (InterruptedExcepIon e) {}
}
});
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Final balance: " + [Link]());
}
}
ExecutorService
import [Link].*;
import [Link];
import [Link];
public class ExecutorServiceExample {
// Task yang mengembalikan hasil
staIc class CalculaIonTask implements Callable<Integer> {
private int number;
public CalculaIonTask(int number) {
[Link] = number;
}
@Override
public Integer call() throws ExcepIon {
[Link](1000); // Simulasi operasi berat
int result = number * number;
[Link]("Calculated " + number + "^2 = " + result);
return result;
}
}
public staIc void main(String[] args) {
// Fixed Thread Pool
ExecutorService executor = [Link](3);
try {
// Submit tasks yang mengembalikan Future
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
Future<Integer> future = [Link](new CalculaIonTask(i));
[Link](future);
}
// Ambil hasil dari semua tasks
[Link]("Results:");
for (Future<Integer> future : futures) {
try {
Integer result = [Link](); // Blocking call
[Link]("Got result: " + result);
} catch (ExecuIonExcepIon e) {
[Link]("Task failed: " + [Link]());
}
}
// Submit simple Runnable tasks
for (int i = 1; i <= 3; i++) {
final int taskId = i;
[Link](() -> {
[Link]("Simple task " + taskId + " executed by " +
[Link]().getName());
});
}
} catch (InterruptedExcepIon e) {
[Link]().interrupt();
} finally {
// Shutdown executor
[Link]();
try {
if () {
[Link]();
}
} catch (InterruptedExcepIon e) {
[Link]();
}
}
// Scheduled Executor Example
ScheduledExecutorService scheduler = [Link](2);
// Schedule task dengan delay
[Link](() -> {
[Link]("Delayed task executed");
}, 2, [Link]);
// Schedule task dengan fixed rate
ScheduledFuture<?> periodicTask = [Link](() -> {
[Link]("Periodic task - " + [Link]());
}, 1, 3, [Link]);
// Cancel periodic task setelah 10 deIk
[Link](() -> {
[Link](false);
[Link]("Periodic task cancelled");
[Link]();
}, 10, [Link]);
}
}
14. Database ConnecAvity
JDBC Basics
import [Link].*;
import [Link];
import [Link];
// Model class untuk data
class Employee {
private int id;
private String name;
private String email;
private double salary;
// Constructors
public Employee() {}
public Employee(String name, String email, double salary) {
[Link] = name;
[Link] = email;
[Link] = salary;
}
// Ge‚ers dan se‚ers
public int getId() { return id; }
public void setId(int id) { [Link] = id; }
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public String getEmail() { return email; }
public void setEmail(String email) { [Link] = email; }
public double getSalary() { return salary; }
public void setSalary(double salary) { [Link] = salary; }
@Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + "', email='" + email +
"', salary=" + salary + "}";
}
}
// Database Access Object (DAO)
class EmployeeDAO {
private staIc final String DB_URL = "jdbc:mysql://localhost:3306/company";
private staIc final String USERNAME = "root";
private staIc final String PASSWORD = "password";
// Establish database connecIon
private ConnecIon getConnecIon() throws SQLExcepIon {
return [Link](DB_URL, USERNAME, PASSWORD);
}
// Create table
public void createTable() {
String sql = """
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
salary DOUBLE NOT NULL
)
""";
try (ConnecIon conn = getConnecIon();
Statement stmt = [Link]()) {
[Link](sql);
[Link]("Table created successfully");
} catch (SQLExcepIon e) {
[Link]("Error creaIng table: " + [Link]());
}
}
// Insert employee
public boolean insertEmployee(Employee employee) {
String sql = "INSERT INTO employees (name, email, salary) VALUES (?, ?, ?)";
try (ConnecIon conn = getConnecIon();
PreparedStatement pstmt = [Link](sql,
Statement.RETURN_GENERATED_KEYS)) {
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
int affectedRows = [Link]();
if (affectedRows > 0) {
// Get generated ID
try (ResultSet generatedKeys = [Link]()) {
if ([Link]()) {
[Link]([Link](1));
}
}
return true;
}
} catch (SQLExcepIon e) {
[Link]("Error inserIng employee: " + [Link]());
}
return false;
}
// Get all employees
public List<Employee> getAllEmployees() {
List<Employee> employees = new ArrayList<>();
String sql = "SELECT * FROM employees";
try (ConnecIon conn = getConnecIon();
Statement stmt = [Link]();
ResultSet rs = [Link](sql)) {
while ([Link]()) {
Employee emp = new Employee();
[Link]([Link]("id"));
[Link]([Link]("name"));
[Link]([Link]("email"));
[Link]([Link]("salary"));
[Link](emp);
}
} catch (SQLExcepIon e) {
[Link]("Error ge‡ng employees: " + [Link]());
}
return employees;
}
// Get employee by ID
public Employee getEmployeeById(int id) {
String sql = "SELECT * FROM employees WHERE id = ?";
try (ConnecIon conn = getConnecIon();
PreparedStatement pstmt = [Link](sql)) {
[Link](1, id);
ResultSet rs = [Link]();
if ([Link]()) {
Employee emp = new Employee();
[Link]([Link]("id"));
[Link]([Link]("name"));
[Link]([Link]("email"));
[Link]([Link]("salary"));
return emp;
}
} catch (SQLExcepIon e) {
[Link]("Error ge‡ng employee: " + [Link]());
}
return null;
}
// Update employee
public boolean updateEmployee(Employee employee) {
String sql = "UPDATE employees SET name = ?, email = ?, salary = ? WHERE id = ?";
try (ConnecIon conn = getConnecIon();
PreparedStatement pstmt = [Link](sql)) {
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
return [Link]() > 0;
} catch (SQLExcepIon e) {
[Link]("Error updaIng employee: " + [Link]());
}
return false;
}
// Delete employee
public boolean deleteEmployee(int id) {
String sql = "DELETE FROM employees WHERE id = ?";
try (ConnecIon conn = getConnecIon();
PreparedStatement pstmt = [Link](sql)) {
[Link](1, id);
return [Link]() > 0;
} catch (SQLExcepIon e) {
[Link]("Error deleIng employee: " + [Link]());
}
return false;
}
// Search employees by name
public List<Employee> searchEmployeesByName(String searchTerm) {
List<Employee> employees = new ArrayList<>();
String sql = "SELECT * FROM employees WHERE name LIKE ?";
try (ConnecIon conn = getConnecIon();
PreparedStatement pstmt = [Link](sql)) {
[Link](1, "%" + searchTerm + "%");
ResultSet rs = [Link]();
while ([Link]()) {
Employee emp = new Employee();
[Link]([Link]("id"));
[Link]([Link]("name"));
[Link]([Link]("email"));
[Link]([Link]("salary"));
[Link](emp);
}
} catch (SQLExcepIon e) {
[Link]("Error searching employees: " + [Link]());
}
return employees;
}
}
// Demo penggunaan JDBC
public class JDBCDemo {
public staIc void main(String[] args) {
EmployeeDAO dao = new EmployeeDAO();
// Create table
[Link]();
// Insert employees
Employee emp1 = new Employee("John Doe", "john@[Link]", 50000);
Employee emp2 = new Employee("Jane Smith", "jane@[Link]", 60000);
Employee emp3 = new Employee("Bob Johnson", "bob@[Link]", 55000);
if ([Link](emp1)) {
[Link]("Employee inserted: " + emp1);
}
[Link](emp2);
[Link](emp3);
// Get all employees
[Link]("\nAll Employees:");
List<Employee> allEmployees = [Link]();
[Link]([Link]::println);
// Get employee by ID
Employee foundEmp = [Link](1);
if (foundEmp != null) {
[Link]("\nFound employee: " + foundEmp);
}
// Update employee
if (foundEmp != null) {
[Link](55000);
if ([Link](foundEmp)) {
[Link]("Employee updated: " + foundEmp);
}
}
// Search employees
[Link]("\nSearch results for 'John':");
List<Employee> searchResults = [Link]("John");
[Link]([Link]::println);
// Delete employee
if ([Link](3)) {
[Link]("Employee with ID 3 deleted");
}
// Final list
[Link]("\nFinal employee list:");
[Link]().forEach([Link]::println);
}
}
15. Best PracAces
Code Style dan ConvenAon
// Good naming convenIons
public class CustomerOrderManager {
// Constants in UPPER_CASE
private staIc final int MAX_RETRY_ATTEMPTS = 3;
private staIc final String DEFAULT_CURRENCY = "USD";
// Instance variables in camelCase
private List<Order> pendingOrders;
private PaymentProcessor paymentProcessor;
// Method names should be verbs in camelCase
public boolean processCustomerOrder(Customer customer, List<OrderItem> items) {
// Local variables in camelCase
double totalAmount = calculateTotalAmount(items);
// Use meaningful variable names
boolean isValidCustomer = validateCustomer(customer);
boolean hasAvailableStock = checkStockAvailability(items);
if (!isValidCustomer || !hasAvailableStock) {
return false;
}
return createAndProcessOrder(customer, items, totalAmount);
}
// Private methods should also follow camelCase
private double calculateTotalAmount(List<OrderItem> items) {
return [Link]()
.mapToDouble(OrderItem::getPrice)
.sum();
}
private boolean validateCustomer(Customer customer) {
return customer != null &&
[Link]() > 0 &&
[Link]() != null &&
![Link]().trim().isEmpty();
}
private boolean checkStockAvailability(List<OrderItem> items) {
// ImplementaIon here
return true; // Simplified
}
private boolean createAndProcessOrder(Customer customer, List<OrderItem> items,
double amount) {
// ImplementaIon here
return true; // Simplified
}
}
// Contoh class dengan proper encapsulaIon
class OrderItem {
private final String productId;
private final String productName;
private final double price;
private final int quanIty;
// Constructor validaIon
public OrderItem(String productId, String productName, double price, int quanIty) {
if (productId == null || [Link]().isEmpty()) {
throw new IllegalArgumentExcepIon("Product ID cannot be null or empty");
}
if (price < 0) {
throw new IllegalArgumentExcepIon("Price cannot be negaIve");
}
if (quanIty <= 0) {
throw new IllegalArgumentExcepIon("QuanIty must be posiIve");
}
[Link] = productId;
[Link] = productName;
[Link] = price;
[Link] = quanIty;
}
// Only ge‚ers for immutable class
public String getProductId() { return productId; }
public String getProductName() { return productName; }
public double getPrice() { return price; }
public int getQuanIty() { return quanIty; }
public double getTotalPrice() {
return price * quanIty;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != [Link]()) return false;
OrderItem orderItem = (OrderItem) obj;
return [Link]([Link], price) == 0 &&
quanIty == [Link] &&
[Link]([Link]) &&
[Link]([Link]);
}
@Override
public int hashCode() {
return [Link](productId, productName, price, quanIty);
}
@Override
public String toString() {
return "OrderItem{" +
"productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", quanIty=" + quanIty +
'}';
}
}
Design Pagerns
// Singleton Pa‚ern
public class DatabaseConnecIon {
private staIc DatabaseConnecIon instance;
private ConnecIon connecIon;
private DatabaseConnecIon() {
// Private constructor
iniIalizeConnecIon();
}
public staIc synchronized DatabaseConnecIon getInstance() {
if (instance == null) {
instance = new DatabaseConnecIon();
}
return instance;
}
private void iniIalizeConnecIon() {
// Database connecIon logic
}
public ConnecIon getConnecIon() {
return connecIon;
}
}
// Factory Pa‚ern
abstract class Vehicle {
public abstract void start();
public abstract void stop();
}
class Car extends Vehicle {
@Override
public void start() {
[Link]("Car started");
}
@Override
public void stop() {
[Link]("Car stopped");
}
}
class Motorcycle extends Vehicle {
@Override
public void start() {
[Link]("Motorcycle started");
}
@Override
public void stop() {
[Link]("Motorcycle stopped");
}
}
class VehicleFactory {
public staIc Vehicle createVehicle(String type) {
switch ([Link]()) {
case "car":
return new Car();
case "motorcycle":
return new Motorcycle();
default:
throw new IllegalArgumentExcepIon("Unknown vehicle type: " + type);
}
}
}
// Observer Pa‚ern
import [Link].*;
interface Observer {
void update(String message);
}
interface Subject {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void noIfyObservers(String message);
}
class NewsAgency implements Subject {
private List<Observer> observers = new ArrayList<>();
private String news;
@Override
public void addObserver(Observer observer) {
[Link](observer);
}
@Override
public void removeObserver(Observer observer) {
[Link](observer);
}
@Override
public void noIfyObservers(String message) {
for (Observer observer : observers) {
[Link](message);
}
}
public void setNews(String news) {
[Link] = news;
noIfyObservers("Breaking News: " + news);
}
}
class NewsChannel implements Observer {
private String name;
public NewsChannel(String name) {
[Link] = name;
}
@Override
public void update(String message) {
[Link](name + " received: " + message);
}
}
Error Handling Best PracAces
public class BestPracIcesDemo {
// Use specific excepIons
public void processFile(String filename) throws FileNotFoundExcepIon, SecurityExcepIon
{
if (filename == null || fi[Link]().isEmpty()) {
throw new IllegalArgumentExcepIon("Filename cannot be null or empty");
}
File file = new File(filename);
if (!fi[Link]()) {
throw new FileNotFoundExcepIon("File not found: " + filename);
}
if (!fi[Link]()) {
throw new SecurityExcepIon("No read permission for file: " + filename);
}
// Process file logic here
}
// Proper resource management
public String readFileContent(String filename) {
StringBuilder content = new StringBuilder();
// Try-with-resources ensures proper cleanup
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = [Link]()) != null) {
[Link](line).append("\n");
}
} catch (IOExcepIon e) {
[Link]("Error reading file: " + [Link]());
return null;
}
return [Link]();
}
// Input validaIon
public double divide(double dividend, double divisor) {
if ([Link](dividend) || [Link](divisor)) {
throw new IllegalArgumentExcepIon("Arguments cannot be NaN");
}
if ([Link]finite(dividend) || [Link]finite(divisor)) {
throw new IllegalArgumentExcepIon("Arguments cannot be infinite");
}
if (divisor == 0.0) {
throw new ArithmeIcExcepIon("Division by zero");
}
return dividend / divisor;
}
// Logging instead of [Link]
private staIc final Logger logger = [Link]([Link]());
public void demonstrateLogging() {
[Link]("ApplicaIon started");
try {
// Some operaIon
processFile("[Link]");
[Link]("File processed successfully");
} catch (FileNotFoundExcepIon e) {
[Link]("File not found: " + [Link]());
} catch (SecurityExcepIon e) {
[Link]("Security error: " + [Link]());
} catch (ExcepIon e) {
[Link]("Unexpected error: " + [Link]());
}
}
}
Performance Best PracAces
import [Link];
public class PerformanceTips {
// Use StringBuilder for string concatenaIon
public String buildString(List<String> items) {
StringBuilder sb = new StringBuilder();
for (String item : items) {
[Link](item).append(", ");
}
// Remove trailing comma and space
if ([Link]() > 0) {
[Link]([Link]() - 2);
}
return [Link]();
}
// Use appropriate collecIon types
private Map<String, String> cache = new ConcurrentHashMap<>(); // Thread-safe
private Set<String> uniqueItems = new HashSet<>(); // Fast lookup
private List<String> orderedItems = new ArrayList<>(); // Random access
// Lazy iniIalizaIon
private List<String> expensiveList;
public List<String> getExpensiveList() {
if (expensiveList == null) {
expensiveList = createExpensiveList();
}
return expensiveList;
}
private List<String> createExpensiveList() {
// Expensive operaIon
return new ArrayList<>();
}
// Use streams efficiently
public List<String> processItems(List<String> items) {
return [Link]()
.filter(item -> item != null && ![Link]())
.map(String::trim)
.map(String::toLowerCase)
.disInct()
.sorted()
.collect([Link]());
}
// Avoid creaIng unnecessary objects
public boolean isValidEmail(String email) {
if (email == null || [Link]()) {
return false;
}
// Use regex pa‚ern as staIc final for reuse
return EMAIL_PATTERN.matcher(email).matches();
}
private staIc final Pa‚ern EMAIL_PATTERN =
Pa‚[Link]("^[A-Za-z0-9+_.-]+@(.+)$");
}
16. Project Akhir
Library Management System
// Project: Sistem Manajemen Perpustakaan
import [Link];
import [Link]‚er;
import [Link].*;
import [Link];
// Model Classes
class Book {
private String isbn;
private String Itle;
private String author;
private String category;
private boolean isAvailable;
private LocalDate publishedDate;
public Book(String isbn, String Itle, String author, String category, LocalDate
publishedDate) {
[Link] = isbn;
[Link] = Itle;
[Link] = author;
[Link] = category;
[Link] = publishedDate;
[Link] = true;
}
// Ge‚ers dan se‚ers
public String getIsbn() { return isbn; }
public String getTitle() { return Itle; }
public String getAuthor() { return author; }
public String getCategory() { return category; }
public boolean isAvailable() { return isAvailable; }
public void setAvailable(boolean available) { isAvailable = available; }
public LocalDate getPublishedDate() { return publishedDate; }
@Override
public String toString() {
return [Link]("Book{ISBN='%s', Itle='%s', author='%s', category='%s',
available=%s, published=%s}",
isbn, Itle, author, category, isAvailable,
[Link](DateTimeForma‚er.ISO_LOCAL_DATE));
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != [Link]()) return false;
Book book = (Book) obj;
return [Link](isbn, [Link]);
}
@Override
public int hashCode() {
return [Link](isbn);
}
}
class Member {
private String memberId;
private String name;
private String email;
private LocalDate joinDate;
private List<String> borrowedBooks;
public Member(String memberId, String name, String email) {
[Link] = memberId;
[Link] = name;
[Link] = email;
[Link] = [Link]();
[Link] = new ArrayList<>();
}
public String getMemberId() { return memberId; }
public String getName() { return name; }
public String getEmail() { return email; }
public LocalDate getJoinDate() { return joinDate; }
public List<String> getBorrowedBooks() { return new ArrayList<>(borrowedBooks); }
public void addBorrowedBook(String isbn) {
[Link](isbn);
}
public boolean removeBorrowedBook(String isbn) {
return [Link](isbn);
}
public int getBorrowedBooksCount() {
return [Link]();
}
@Override
public String toString() {
return [Link]("Member{ID='%s', name='%s', email='%s', joined=%s,
borrowed=%d}",
memberId, name, email, [Link](DateTimeForma‚er.ISO_LOCAL_DATE),
[Link]());
}
}
class BorrowRecord {
private String recordId;
private String memberId;
private String isbn;
private LocalDate borrowDate;
private LocalDate dueDate;
private LocalDate returnDate;
public BorrowRecord(String memberId, String isbn) {
[Link] = generateRecordId();
[Link] = memberId;
[Link] = isbn;
[Link] = [Link]();
[Link] = [Link](2); // 2 weeks loan period
}
private String generateRecordId() {
return "BR" + [Link]();
}
// Ge‚ers dan se‚ers
public String getRecordId() { return recordId; }
public String getMemberId() { return memberId; }
public String getIsbn() { return isbn; }
public LocalDate getBorrowDate() { return borrowDate; }
public LocalDate getDueDate() { return dueDate; }
public LocalDate getReturnDate() { return returnDate; }
public void setReturnDate(LocalDate returnDate) { [Link] = returnDate; }
public boolean isOverdue() {
return returnDate == null && [Link]().isA€er(dueDate);
}
public boolean isReturned() {
return returnDate != null;
}
@Override
public String toString() {
String status = isReturned() ? "Returned" : (isOverdue() ? "Overdue" : "AcIve");
return [Link]("BorrowRecord{ID='%s', member='%s', ISBN='%s', borrowed=%s,
due=%s, status=%s}",
recordId, memberId, isbn,
[Link](DateTimeForma‚er.ISO_LOCAL_DATE),
[Link](DateTimeForma‚er.ISO_LOCAL_DATE), status);
}
}
// Custom ExcepIons
class BookNotFoundExcepIon extends ExcepIon {
public BookNotFoundExcepIon(String message) {
super(message);
}
}
class MemberNotFoundExcepIon extends ExcepIon {
public MemberNotFoundExcepIon(String message) {
super(message);
}
}
class BookNotAvailableExcepIon extends ExcepIon {
public BookNotAvailableExcepIon(String message) {
super(message);
}
}
// Library Management System
class LibraryManager {
private Map<String, Book> books;
private Map<String, Member> members;
private List<BorrowRecord> borrowRecords;
private staIc final int MAX_BOOKS_PER_MEMBER = 3;
public LibraryManager() {
[Link] = new HashMap<>();
[Link] = new HashMap<>();
[Link] = new ArrayList<>();
}
// Book Management
public void addBook(Book book) {
[Link]([Link](), book);
[Link]("Book added: " + [Link]());
}
public void removeBook(String isbn) throws BookNotFoundExcepIon {
Book book = [Link](isbn);
if (book == null) {
throw new BookNotFoundExcepIon("Book with ISBN " + isbn + " not found");
}
[Link]("Book removed: " + [Link]());
}
public Book findBook(String isbn) throws BookNotFoundExcepIon {
Book book = [Link](isbn);
if (book == null) {
throw new BookNotFoundExcepIon("Book with ISBN " + isbn + " not found");
}
return book;
}
public List<Book> searchBooksByTitle(String Itle) {
return [Link]().stream()
.filter(book -> [Link]().toLowerCase().contains([Link]()))
.collect([Link]());
}
public List<Book> searchBooksByAuthor(String author) {
return [Link]().stream()
.filter(book -> [Link]().toLowerCase().contains([Link]()))
.collect([Link]());
}
public List<Book> getAvailableBooks() {
return [Link]().stream()
.filter(Book::isAvailable)
.collect([Link]());
}
// Member Management
public void addMember(Member member) {
[Link]([Link](), member);
[Link]("Member added: " + [Link]());
}
public void removeMember(String memberId) throws MemberNotFoundExcepIon {
Member member = [Link](memberId);
if (member == null) {
throw new MemberNotFoundExcepIon("Member with ID " + memberId + " not
found");
}
[Link]("Member removed: " + [Link]());
}
public Member findMember(String memberId) throws MemberNotFoundExcepIon {
Member member = [Link](memberId);
if (member == null) {
throw new MemberNotFoundExcepIon("Member with ID " + memberId + " not
found");
}
return member;
}
// Borrowing System
public void borrowBook(String memberId, String isbn)
throws MemberNotFoundExcepIon, BookNotFoundExcepIon,
BookNotAvailableExcepIon {
Member member = findMember(memberId);
Book book = findBook(isbn);
if (![Link]()) {
throw new BookNotAvailableExcepIon("Book '" + [Link]() + "' is not
available");
}
if ([Link]() >= MAX_BOOKS_PER_MEMBER) {
throw new BookNotAvailableExcepIon("Member has reached maximum borrowing
limit");
}
// Create borrow record
BorrowRecord record = new BorrowRecord(memberId, isbn);
[Link](record);
// Update book and member
[Link](false);
[Link](isbn);
[Link]("Book borrowed successfully: " + [Link]() + " by " +
[Link]());
}
public void returnBook(String memberId, String isbn)
throws MemberNotFoundExcepIon, BookNotFoundExcepIon {
Member member = findMember(memberId);
Book book = findBook(isbn);
// Find acIve borrow record
BorrowRecord record = [Link]()
.filter(r -> [Link]().equals(memberId) &&
[Link]().equals(isbn) &&
![Link]())
.findFirst()
.orElse(null);
if (record == null) {
throw new BookNotFoundExcepIon("No acIve borrow record found for this book
and member");
}
// Update record, book, and member
[Link]([Link]());
[Link](true);
[Link](isbn);
[Link]("Book returned successfully: " + [Link]() + " by " +
[Link]());
if ([Link]()) {
[Link]("Warning: Book was returned late!");
}
}
// ReporIng
public List<BorrowRecord> getOverdueBooks() {
return [Link]()
.filter(BorrowRecord::isOverdue)
.collect([Link]());
}
public List<BorrowRecord> getMemberBorrowHistory(String memberId) {
return [Link]()
.filter(record -> [Link]().equals(memberId))
.collect([Link]());
}
public void generateReport() {
[Link]("\n=== LIBRARY REPORT ===");
[Link]("Total Books: " + [Link]());
[Link]("Available Books: " + getAvailableBooks().size());
[Link]("Total Members: " + [Link]());
[Link]("AcIve Borrows: " + [Link]()
.filter(r -> ![Link]()).count());
[Link]("Overdue Books: " + getOverdueBooks().size());
[Link]("\nOverdue Books:");
getOverdueBooks().forEach([Link]::println);
}
public List<Book> getAllBooks() {
return new ArrayList<>([Link]());
}
public List<Member> getAllMembers() {
return new ArrayList<>([Link]());
}
}
// Main ApplicaIon
public class LibraryManagementSystem {
private LibraryManager libraryManager;
private Scanner scanner;
public LibraryManagementSystem() {
[Link] = new LibraryManager();
[Link] = new Scanner([Link]);
iniIalizeSampleData();
}
private void iniIalizeSampleData() {
// Add sample books
[Link](new Book("978-0134685991", "EffecIve Java", "Joshua Bloch",
"Programming", [Link](2017, 12, 27)));
[Link](new Book("978-0596009205", "Head First Design Pa‚erns",
"Eric Freeman", "Programming", [Link](2004, 10, 25)));
[Link](new Book("978-0135957059", "The PragmaIc Programmer",
"David Thomas", "Programming", [Link](2019, 9, 13)));
// Add sample members
[Link](new Member("M001", "Alice Johnson",
"alice@[Link]"));
[Link](new Member("M002", "Bob Smith", "bob@[Link]"));
[Link](new Member("M003", "Charlie Brown",
"charlie@[Link]"));
}
public void run() {
[Link]("Welcome to Library Management System!");
while (true) {
showMenu();
int choice = getIntInput("Enter your choice: ");
try {
switch (choice) {
case 1: addBook(); break;
case 2: searchBooks(); break;
case 3: addMember(); break;
case 4: borrowBook(); break;
case 5: returnBook(); break;
case 6: viewMemberHistory(); break;
case 7: [Link](); break;
case 8: listAllBooks(); break;
case 9: listAllMembers(); break;
case 0:
[Link]("Thank you for using Library Management System!");
return;
default:
[Link]("Invalid choice. Please try again.");
}
} catch (ExcepIon e) {
[Link]("Error: " + [Link]());
}
[Link](); // Empty line for readability
}
}
private void showMenu() {
[Link]("\n=== LIBRARY MENU ===");
[Link]("1. Add Book");
[Link]("2. Search Books");
[Link]("3. Add Member");
[Link]("4. Borrow Book");
[Link]("5. Return Book");
[Link]("6. View Member History");
[Link]("7. Generate Report");
[Link]("8. List All Books");
[Link]("9. List All Members");
[Link]("0. Exit");
}
private void addBook() {
[Link]("\n--- Add New Book ---");
String isbn = getStringInput("Enter ISBN: ");
String Itle = getStringInput("Enter Title: ");
String author = getStringInput("Enter Author: ");
String category = getStringInput("Enter Category: ");
[Link]("Enter Published Date (YYYY-MM-DD): ");
String dateStr = [Link]();
LocalDate publishedDate = [Link](dateStr);
Book book = new Book(isbn, Itle, author, category, publishedDate);
[Link](book);
}
private void searchBooks() {
[Link]("\n--- Search Books ---");
[Link]("1. Search by Title");
[Link]("2. Search by Author");
[Link]("3. List Available Books");
int choice = getIntInput("Enter search type: ");
List<Book> results = new ArrayList<>();
switch (choice) {
case 1:
String Itle = getStringInput("Enter Itle to search: ");
results = [Link](Itle);
break;
case 2:
String author = getStringInput("Enter author to search: ");
results = [Link](author);
break;
case 3:
results = [Link]();
break;
default:
[Link]("Invalid choice");
return;
}
if ([Link]()) {
[Link]("No books found");
} else {
[Link]("Search Results:");
[Link]([Link]::println);
}
}
private void addMember() {
[Link]("\n--- Add New Member ---");
String memberId = getStringInput("Enter Member ID: ");
String name = getStringInput("Enter Name: ");
String email = getStringInput("Enter Email: ");
Member member = new Member(memberId, name, email);
[Link](member);
}
private void borrowBook() throws MemberNotFoundExcepIon, BookNotFoundExcepIon,
BookNotAvailableExcepIon {
[Link]("\n--- Borrow Book ---");
String memberId = getStringInput("Enter Member ID: ");
String isbn = getStringInput("Enter Book ISBN: ");
[Link](memberId, isbn);
}
private void returnBook() throws MemberNotFoundExcepIon, BookNotFoundExcepIon {
[Link]("\n--- Return Book ---");
String memberId = getStringInput("Enter Member ID: ");
String isbn = getStringInput("Enter Book ISBN: ");
[Link](memberId, isbn);
}
private void viewMemberHistory() {
[Link]("\n--- Member Borrow History ---");
String memberId = getStringInput("Enter Member ID: ");
List<BorrowRecord> history = [Link](memberId);
if ([Link]()) {
[Link]("No borrow history found for member: " + memberId);
} else {
[Link]("Borrow History:");
[Link]([Link]::println);
}
}
private void listAllBooks() {
[Link]("\n--- All Books ---");
List<Book> books = [Link]();
if ([Link]()) {
[Link]("No books in library");
} else {
[Link]([Link]::println);
}
}
private void listAllMembers() {
[Link]("\n--- All Members ---");
List<Member> members = [Link]();
if ([Link]()) {
[Link]("No members registered");
} else {
[Link]([Link]::println);
}
}
private String getStringInput(String prompt) {
[Link](prompt);
return [Link]().trim();
}
private int getIntInput(String prompt) {
while (true) {
try {
[Link](prompt);
return [Link]([Link]().trim());
} catch (NumberFormatExcepIon e) {
[Link]("Invalid number. Please try again.");
}
}
}
public staIc void main(String[] args) {
LibraryManagementSystem system = new LibraryManagementSystem();
[Link]();
}
}
Kesimpulan
Selamat! Anda telah menyelesaikan e-book pemrograman Java ini yang mencakup berbagai
aspek penIng dari bahasa pemrograman Java, mulai dari konsep dasar hingga topik-topik
lanjutan.
Apa yang Telah Anda Pelajari:
1. Dasar-dasar Java: Sintaks, variabel, Ipe data, dan operator
2. Struktur Kontrol: Decision making dan looping
3. Array dan CollecAons: Struktur data penIng untuk menyimpan dan mengelola data
4. Method dan FuncAon: Memecah kode menjadi unit-unit yang dapat digunakan
kembali
5. Object-Oriented Programming: Paradigma utama dalam Java
6. ExcepAon Handling: Menangani error dan situasi Idak terduga
7. File I/O: Membaca dan menulis data dari/ke file
8. Generic Programming: Menulis kode yang type-safe dan reusable
9. MulA-threading: Pemrograman concurrent
10. Database ConnecAvity: Integrasi dengan database
11. Best PracAces: PrakIk terbaik dalam pengembangan Java
12. Project Akhir: Implementasi sistem manajemen perpustakaan
Langkah Selanjutnya:
1. PrakAk Lebih Banyak: Buat project-project kecil untuk memperkuat pemahaman
2. Eksplorasi Framework: Pelajari Spring Boot, Hibernate, atau framework Java lainnya
3. Web Development: Pelajari Java servlet, JSP, atau RESTful API
4. Mobile Development: Coba Android development dengan Java
5. Enterprise Development: Pelajari Java EE atau Jakarta EE
6. TesAng: Pelajari JUnit dan tesIng best pracIces
7. Build Tools: Familiarize dengan