Podręcznik użytkownika Java
Twój pierwszy program w Java
Tworzenie Hello World
Utwórz nowy plik tekstowy o nazwie HelloWorld.java. Zwróć uwagę, że nazwa pliku musi dokładnie odpowiadać nazwie klasy.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Kompilowanie programu
Otwórz terminal lub wiersz poleceń, przejdź do katalogu z plikiem i uruchom polecenie kompilacji:
javac HelloWorld.java
Po udanej kompilacji zostanie wygenerowany plik HelloWorld.class.
Uruchamianie programu
java HelloWorld
Wyjście:
Hello, World!
Podstawowa składnia Java
Zmienne i typy danych
Java jest językiem o statycznie określonych typach. Zmienne muszą być zadeklarowane przed użyciem.
// Primitive data types
int age = 25;
double salary = 5000.50;
boolean isActive = true;
char grade = 'A';
String name = "John";
// Reference types
Integer count = 10;
Double price = 99.99;
Operatory
// Arithmetic operators
int a = 10, b = 3;
int sum = a + b; // Addition
int diff = a - b; // Subtraction
int prod = a * b; // Multiplication
int quot = a / b; // Division
int rem = a % b; // Remainder
// Comparison operators
boolean result = (a > b);
// Logical operators
boolean flag = (a > 5) && (b < 10);
Instrukcje warunkowe
// if-else statement
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
// switch statement
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Unknown");
}
Instrukcje pętli
// for loop
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
// while loop
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
// do-while loop
do {
System.out.println(i);
i++;
} while (i < 10);
// for-each for arrays
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
Programowanie obiektowe
Klasy i obiekty
// Define a class
public class Person {
// Fields
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter and Setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Method
public void sayHello() {
System.out.println("Hello, I'm " + name);
}
}
// Create object
Person person = new Person("John", 25);
person.sayHello();
Dziedziczenie
// Parent class
public class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
// Subclass
public class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}
Interfejsy
public interface Drawable {
void draw();
}
public class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
Polimorfizm
// Parent reference pointing to subclass object
Animal animal = new Dog();
animal.eat(); // Calls Dog's eat method
Framework kolekcji
Interfejs List
import java.util.ArrayList;
import java.util.List;
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
// Iterate
for (String fruit : list) {
System.out.println(fruit);
}
Interfejs Map
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 5);
map.put("Banana", 3);
map.put("Orange", 8);
// Get value
int count = map.get("Apple");
// Iterate
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Interfejs Set
import java.util.HashSet;
import java.util.Set;
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("A"); // Duplicate will not be added
Obsługa wyjątków
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Divisor cannot be zero");
} finally {
System.out.println("Always executes");
}
// Throwing an exception
public void checkAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
Typy generyczne
// Generic class
public class Box<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
}
// Usage
Box<Integer> intBox = new Box<>();
intBox.set(100);
Integer value = intBox.get();
Wyrażenia Lambda
// Anonymous inner class
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Running");
}
};
// Lambda expression
Runnable r2 = () -> System.out.println("Running");
// Lambda with parameters
Comparator<String> c = (s1, s2) -> s1.compareTo(s2);
API Stream
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Filter
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// Map
List<Integer> squared = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
// Sum
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
Operacje na plikach
Odczytywanie plików
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
try {
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Zapisywanie plików
import java.nio.file.Files;
import java.nio.file.Paths;
try {
String content = "Hello, Java!";
Files.write(Paths.get("output.txt"), content.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
Programowanie wielowątkowe
Tworzenie wątków
// Extending Thread class
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running");
}
}
// Implementing Runnable interface
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running");
}
}
// Start thread
MyThread thread = new MyThread();
thread.start();
// Using Runnable
Thread runnableThread = new Thread(new MyRunnable());
runnableThread.start();
Synchronizacja wątków
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
Programowanie sieciowe
Komunikacja TCP
import java.net.*;
import java.io.*;
ServerSocket serverSocket = new ServerSocket(8080);
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
String message = in.readLine();
out.println("Server received: " + message);
Żądania HTTP
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/data"))
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
Operacje na bazach danych
Połączenie JDBC
import java.sql.*;
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String sql = "SELECT * FROM users WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
Popularne klasy narzędziowe
StringBuilder
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
Klasa narzędziowa Arrays
int[] arr = {5, 2, 8, 1, 9};
Arrays.sort(arr); // Sort
Arrays.fill(arr, 0); // Fill
System.out.println(Arrays.toString(arr));
Klasa narzędziowa Collections
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(1);
list.add(2);
Collections.sort(list);
Collections.reverse(list);
Collections.shuffle(list);
