### Simple Enum Class Formatting Example Source: https://google.github.io/styleguide/javaguide.html/index Illustrates a concise formatting style for enum classes that have no methods or constant documentation, resembling an array initializer. ```java private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS } ``` -------------------------------- ### Variable Declaration Example (Not Recommended) Source: https://google.github.io/styleguide/javaguide.html/index Shows an example of multiple variable declarations on a single line, which is not recommended by the Google Style Guide, with the exception of for loop headers. ```java int a, b; ``` -------------------------------- ### Line Wrapping Examples in Java Source: https://google.github.io/styleguide/javaguide.html/index Demonstrates various scenarios for line wrapping in Java, including lambda expressions, predicate assignments, and switch rules. It adheres to syntactic levels and operator precedence for breaks. ```java MyLambda lambda = (String label, Long value, Object obj) -> { ... }; Predicate predicate = str -> longExpressionInvolving(str); switch (x) { case ColorPoint(Color color, Point(int x, int y)) -> handleColorPoint(color, x, y); ... } ``` -------------------------------- ### Javadoc Summary Fragment Example (Java) Source: https://google.github.io/styleguide/javaguide.html/index Demonstrates the correct format for a Javadoc summary fragment, which should be a concise phrase and not a complete sentence. It also shows the preferred use of {@return} over @return for return descriptions. ```java /** * Returns the customer ID. */ public String getCustomerId() { // ... implementation ... } /** * {@return the customer ID} */ public String getCustomerIdWithTag() { // ... implementation ... } ``` -------------------------------- ### Horizontal Alignment Example Source: https://google.github.io/styleguide/javaguide.html/index Compares code formatting with and without horizontal alignment. It highlights that while alignment is permitted, it is never required and maintaining it can lead to future issues. ```java private int x; // this is fine private Color color; // this too ``` ```java private int x; // permitted, but future edits private Color color; // may leave it unaligned ``` -------------------------------- ### Enum Class Formatting Example Source: https://google.github.io/styleguide/javaguide.html/index Demonstrates the formatting of an enum class with methods and documentation. It shows optional line breaks after commas and the allowance of additional blank lines. ```java private enum Answer { YES { @Override public String toString() { return "yes"; } }, NO, MAYBE } ``` -------------------------------- ### Java Constant Naming Example Source: https://google.github.io/styleguide/javaguide.html/index Demonstrates the correct naming convention for constants in Java, which uses UPPER_SNAKE_CASE. It also shows examples of what are considered non-constants. ```java // Constants static final int NUMBER = 5; static final ImmutableList NAMES = ImmutableList.of("Ed", "Ann"); static final Map AGES = ImmutableMap.of("Ed", 35, "Ann", 32); static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable static final SomeMutableType[] EMPTY_ARRAY = {}; // Not constants static String nonFinal = "non-final"; final String nonStatic = "non-static"; static final Set mutableCollection = new HashSet(); static final ImmutableSet mutableElements = ImmutableSet.of(mutable); static final ImmutableMap mutableValues = ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2); static final Logger logger = Logger.getLogger(MyClass.getName()); static final String[] nonEmptyArray = {"these", "can", "change"}; ``` -------------------------------- ### Switch Expression Formatting (Java) Source: https://google.github.io/styleguide/javaguide.html/index Demonstrates the formatting of switch expressions in Java, which must use the new-style syntax with arrows. This example shows a switch expression returning a string based on a list's size. ```Java return switch (list.size()) { case 0 -> ""; case 1 -> list.getFirst(); default -> String.join(", ", list); }; ``` -------------------------------- ### TODO Comment Format in Java Source: https://google.github.io/styleguide/javaguide.html/index TODO comments should start with 'TODO:', followed by a bug reference (e.g., crbug.com/12345678), and then an explanation prefixed with a hyphen. This format ensures consistency and aids in tracking. ```java // TODO: crbug.com/12345678 - Remove this after the 2047q4 compatibility window expires. ``` ```java // TODO: @yourusername - File an issue and use a '*' for repetition. ``` -------------------------------- ### New-Style Switch Statement Formatting (Java) Source: https://google.github.io/styleguide/javaguide.html/index Illustrates the formatting of new-style switch statements in Java, which use arrows (`->`) instead of colons. This example shows single-line cases, multi-line cases with continuation indents, and switch rules with blocks. ```Java switch (number) { case 0, 1 -> handleZeroOrOne(); case 2 -> handleTwoWithAnExtremelyLongMethodCallThatWouldNotFitOnTheSameLine(); default -> { logger.atInfo().log("Surprising number %s", number); handleSurprisingNumber(number); } } ``` -------------------------------- ### Basic Javadoc Formatting in Java Source: https://google.github.io/styleguide/javaguide.html/index Shows the basic formatting for Javadoc comments in Java. It includes examples for multi-line and single-line Javadoc blocks. The multi-line format is always acceptable, while the single-line format can be used when the entire comment fits on one line and contains no block tags. ```Java /** * Multiple lines of Javadoc text are written here, * wrapped normally... */ public int method(String p1) { ... } ``` ```Java /** An especially short bit of Javadoc. */ ``` -------------------------------- ### Array Initializer Formatting (Java) Source: https://google.github.io/styleguide/javaguide.html/index Demonstrates optional 'block-like' formatting for array initializers in Java. This style enhances readability for multi-element initializers by placing each element on a new line, aligned within braces. ```Java new int[] { 0, 1, 2, 3 } new int[] { 0, 1, 2, 3, } new int[] { 0, 1, 2, 3 } new int[] {0, 1, 2, 3} ``` -------------------------------- ### Java: Brace Style and Indentation for Nonempty Blocks Source: https://google.github.io/styleguide/javaguide.html/index Demonstrates the Kernighan and Ritchie (K&R) style for nonempty blocks and block-like constructs in Java. It specifies brace placement, line breaks, and indentation rules, including exceptions for limiting local variable scope. ```java return () -> { while (condition()) { method(); } }; return new MyClass() { @Override public void method() { if (condition()) { try { something(); } catch (ProblemException e) { recover(); } } else if (otherCondition()) { somethingElse(); } else { lastThing(); } { int x = foo(); frob(x); } } }; ``` -------------------------------- ### Type-Use Annotation Placement (Java) Source: https://google.github.io/styleguide/javaguide.html/index Illustrates the placement of type-use annotations in Java. These annotations, marked with `@Target(ElementType.TYPE_USE)`, appear immediately before the annotated type, such as a variable declaration or method return type. ```Java final @Nullable String name; public @Nullable Person getPersonByName(String name); ``` -------------------------------- ### Class, Package, and Module Annotations in Java Source: https://google.github.io/styleguide/javaguide.html/index Annotations for class, package, or module declarations should appear immediately after the documentation block, with each annotation on its own line. This formatting does not increase indentation. ```java /** This is a class. */ @Deprecated @CheckReturnValue public final class Frozzler { ... } ``` ```java /** This is a package. */ @Deprecated @CheckReturnValue package com.example.frozzler; ``` ```java /** This is a module. */ @Deprecated @SuppressWarnings("CheckReturnValue") module com.example.frozzler { ... } ``` -------------------------------- ### Block Comment Styles in Java Source: https://google.github.io/styleguide/javaguide.html/index Block comments should be indented at the same level as surrounding code. Both `/* ... */` and `// ...` styles are acceptable. For multi-line `/* ... */` comments, subsequent lines must start with an asterisk aligned with the previous line's asterisk. ```java /* * This is // And so /* Or you can * okay. // is this. * even do this. */ */ ``` -------------------------------- ### Java: Concise Empty Blocks Source: https://google.github.io/styleguide/javaguide.html/index Illustrates acceptable ways to format empty blocks in Java, either using K&R style with line breaks or a concise `{}` format. It highlights that concise empty blocks are not allowed within multi-block statements like try-catch. ```java // This is acceptable void doNothing() {} // This is equally acceptable void doNothingElse() { } // This is not acceptable: No concise empty blocks in a multi-block statement try { doSomething(); } catch (Exception e) {} ``` -------------------------------- ### Field Annotations in Java Source: https://google.github.io/styleguide/javaguide.html/index Annotations for fields appear after the documentation block. Multiple annotations, including parameterized ones, can be placed on the same line. ```java @Partial @Mock DataLoader loader; ``` -------------------------------- ### Method and Constructor Annotations in Java Source: https://google.github.io/styleguide/javaguide.html/index Annotations for method and constructor declarations follow the same rules as class annotations. A single parameterless annotation may optionally appear on the same line as the first line of the signature. ```java @Deprecated @Override public String getNameIfPresent() { ... } ``` ```java @Override public int hashCode() { ... } ``` -------------------------------- ### Java Class and Member Modifier Order Source: https://google.github.io/styleguide/javaguide.html/index Class and member modifiers should follow the order specified by the Java Language Specification. ```java public protected private abstract default static final sealed non-sealed transient volatile synchronized native strictfp ``` -------------------------------- ### Java Module Requires Modifier Order Source: https://google.github.io/styleguide/javaguide.html/index Modifiers for `requires` module directives should appear in the following order: `transitive` then `static`. ```java transitive static ``` -------------------------------- ### Handle Ignored Caught Exceptions in Java Source: https://google.github.io/styleguide/javaguide.html/index Demonstrates how to handle ignored caught exceptions in Java. It shows a try-catch block where a NumberFormatException is caught and ignored, with a comment explaining the reason. This pattern is used when the exception is expected and does not require specific handling. ```Java try { int i = Integer.parseInt(response); return handleNumericResponse(i); } catch (NumberFormatException ok) { // it's not numeric; that's fine, just continue } return handleTextResponse(response); ``` -------------------------------- ### Long-Valued Integer Literals in Java Source: https://google.github.io/styleguide/javaguide.html/index Long-valued integer literals must use an uppercase 'L' suffix to avoid confusion with the digit '1'. ```java 3000000000L ``` -------------------------------- ### Java Non-ASCII Character Handling Source: https://google.github.io/styleguide/javaguide.html/index Illustrates how to handle non-ASCII characters in Java strings, either by using the actual Unicode character or its equivalent Unicode escape sequence. The choice should prioritize readability, with actual characters generally preferred unless they hinder understanding. Comments can clarify the meaning of escapes. ```java String unitAbbrev = "μs"; // Best: perfectly clear String unitAbbrevUnicode = "\u03bcs"; // Allowed, but less clear without context String unitAbbrevComment = "\u03bcs"; // Greek letter mu, "s" - Allowed, but awkward String unitAbbrevPoor = "\u03bcs"; // Poor: reader has no idea what this is return '\ufeff' + content; // Good: use escapes for non-printable characters like byte order mark, and comment if necessary. ``` -------------------------------- ### Java Text Block Formatting Source: https://google.github.io/styleguide/javaguide.html/index The opening `"""` of a text block is on a new line, potentially with no indentation. The closing `"""` is on a new line with the same indentation and may be followed by code. All lines within the text block must be indented at least as much as the opening `"""`. ```java String text = """ This is a text block. It can span multiple lines. """; ``` -------------------------------- ### Old-Style Switch Statement Fall-through (Java) Source: https://google.github.io/styleguide/javaguide.html/index Shows the required 'fall through' comment for old-style switch statements in Java when execution continues to the next case. This comment is necessary unless the statement group is the last one and terminates abruptly. ```Java switch (input) { case 1: case 2: prepareOneOrTwo(); // fall through case 3: handleOneTwoOrThree(); break; default: handleLargeNumber(input); } ``` -------------------------------- ### Java Special Escape Sequences Source: https://google.github.io/styleguide/javaguide.html/index Demonstrates the use of special escape sequences in Java for characters like backspace, tab, newline, form feed, carriage return, space, double quote, single quote, and backslash. These sequences are preferred over octal or Unicode escapes for clarity. ```java String example = "This is a string with a \"double quote\" and a \\backslash.\nIt also includes a \t tab and a \f form feed."; char newlineChar = '\n'; char tabChar = '\t'; char backslashChar = '\\'; ``` -------------------------------- ### Qualify Static Members Using Class Name in Java Source: https://google.github.io/styleguide/javaguide.html/index Illustrates the correct way to qualify static class members in Java. Static members should always be accessed using the class name, not an instance of the class or an expression that yields an instance. This promotes clarity and avoids potential confusion. ```Java Foo aFoo = ...; Foo.aStaticMethod(); // good aFoo.aStaticMethod(); // bad somethingThatYieldsAFoo().aStaticMethod(); // very bad ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.