Declare a variable with a primitive data type
int x = 10;
float y = 20.5f;
boolean z = true;
Declare a variable with a reference data type
String s = 'Hello, world!';
Evaluate a condition and execute code if it's true
if (x > y) {
/* ... */
}
Evaluate another condition if the previous one is false
else if (x < y) {
/* ... */
}
Execute code if all previous conditions are false
else {
/* */
}
Create a loop that iterates a specific number of times
for (int i = 0; i < 10; i++) {
/* ... */
}
Create a loop that continues as long as the condition is true
while (x < 10) {
/* ... */
x++;
}
Execute code once, then repeat the loop as long as the condition is true
do {
/* ... */
x++;
} while (x < 10);
Declare a function with a given name
public static void myFunction() {
/* ... */
}
Declare multiple functions with the same name but different parameters
public static void myFunction(int x) {
/* ... */
}
public static void myFunction(String s) {
/* ... */
}
A function that calls itself
public static int factorial(int n) {
if (n == 1) return 1;
return n * factorial(n - 1);
}
Declare an array
int[] myArray = new int[5];
Initialize an array with values
int[] myArray = {1, 2, 3, 4, 5};
Declare an object of a custom class
MyClass myObject = new MyClass();
Create a subclass that inherits from a parent class
class MySubclass extends MyClass {
/* ... */
}
Handle errors and exceptions using trycatch, and finally blocks
try {
/* ... */
} catch (Exception e) {
/* ... */
} finally {
/* ... */
}
Throw an exception
if (x < 0) {
throw new IllegalArgumentException('x must be non-negative');
}
Create a custom exception class
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
A dynamic, resizable array
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);
myList.remove(0);
A collection of key-value pairs
HashMap<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put('one', 1);
myMap.put('two', 2);
myMap.remove('one');
Create a new thread by extending the Thread class
class MyThread extends Thread {
public void run() {
/* ... */
}
}
MyThread t = new MyThread();
t.start();
Create a new thread by implementing the Runnable interface
class MyRunnable implements Runnable {
public void run() {
/* ... */
}
}
Thread t = new Thread(new MyRunnable());
t.start();
Synchronize a block of code to prevent concurrent access
synchronized (myObject) {
/* ... */
}