Here is a cheat sheet for Java:
- Basic Data Types:
- int: integers (e.g. 5)
- double: floating-point numbers (e.g. 3.14)
- char: characters (e.g. ‘a’)
- boolean: boolean values (true or false)
- String: a sequence of characters (e.g. “hello”)
- Basic Operators:
- +: addition or string concatenation
- -: subtraction
- *: multiplication
- /: division (integer division truncates)
- %: modulo (remainder)
- ++: increment
- –: decrement
- Conditional Statements:
- if statement:
if (condition) {
statement;
} else if (condition) {
statement;
} else {
statement;
}
- ternary operator:
value = (condition) ? value_if_true : value_if_false;
- Loops:
- for loop:
for (int i = 0; i < limit; i++) {
statement;
}
- enhanced for loop (for-each loop):
for (variable : iterable) {
statement;
}
- while loop:
while (condition) {
statement;
}
- do-while loop:
do {
statement;
} while (condition);
- break statement:
while (condition) {
if (condition) {
break;
}
statement;
}
- Arrays:
- creating an array:
int[] my_array = {1, 2, 3, 4, 5};
- accessing an element in an array:
my_array[0]; // returns 1
- iterating over an array:
for (int i = 0; i < my_array.length; i++) {
statement;
}
- ArrayLists:
- creating an ArrayList:
ArrayList<String> my_list = new ArrayList<String>();
my_list.add("item");
- accessing an element in an ArrayList:
my_list.get(0); // returns "item"
- iterating over an ArrayList:
for (String item : my_list) {
statement;
}
- Methods:
- defining a method:
public returnType myMethod(argType1 arg1, argType2 arg2) {
statement;
return value;
}
- calling a method:
myMethod(value1, value2);
- Classes:
- defining a class:
public class MyClass {
// fields
// constructors
// methods
}
- instantiating a class:
MyClass object = new MyClass();
- Packages:
- importing a package:
import java.util.*;
- importing a specific class from a package:
import java.util.ArrayList;
- Exception Handling:
- try/catch block:
try {
statement;
} catch (ExceptionType e) {
statement;
}
- throwing an exception:
throw new ExceptionType("Error message");
This cheat sheet covers some of the most commonly used features in Java, including basic data types, operators, conditional statements, loops, arrays, ArrayLists, methods, classes, packages, and exception handling. Java is a powerful and versatile language used for a wide range of applications, including web development, mobile development, and enterprise software development.