30 Seconds of Java is a curated collection of reusable, copy-pasteable Java 21 snippets designed to be understood in 30 seconds or less. These snippets cover a wide range of common tasks and are automatically published to the project's website via the README.md file.
- Language: Java 21
- Build System: Gradle 8.x
- Testing: JUnit 5 (Jupiter), Hamcrest
- Quality Assurance: Checkstyle, SonarCloud
/src/main/java/{category}/: Source code for the snippets, organized by category (e.g.,string,math,network)./src/test/java/{category}/: Unit tests for each snippet.README.md: The main documentation file containing all snippets, used for website generation.build.gradle: Project dependencies and build configuration.
- Stateless Utility Methods: Implement snippets as
public staticmethods within a dedicated class. - Locale Independence: Always use
Locale.ENGLISHwhen formatting strings (e.g.,String.format) to ensure consistent behavior across different environments. - Modern Java Features: Leverage Java 21 features (e.g.,
var,StreamAPI, modernHttpClient) where appropriate. - Focused Scope: Each snippet class should perform exactly one task or a small set of highly related tasks.
- External Dependencies: Do not add third-party libraries; rely exclusively on the Java Standard Library.
- Global State: Snippets must not maintain or depend on mutable global state.
- Interactive Logic: Avoid snippets that require terminal input or user interaction.
- Untested Code: Every snippet must be accompanied by a comprehensive JUnit test.
A complete snippet implementation consists of three parts:
- Source Code (
src/main/java/string/FormatBytesSnippet.java):
public class FormatBytesSnippet {
public static String formatBytes(long bytes) {
double kb = 1024;
// ... logic ...
return String.format(Locale.ENGLISH, "%.2f MB", bytes / mb);
}
}- Test File (
src/test/java/string/FormatBytesSnippetTest.java):
class FormatBytesSnippetTest {
@Test
void formatBytes() {
assertEquals("1.46 MB", FormatBytesSnippet.formatBytes(1536000));
}
}- README.md Entry:
### Format Bytes
```java
// [Full code of the snippet]