For example, new methods are not just habitually added to the end of the class, as that would yield "chronological by date added" ordering, which is not a logical ordering. When a class has multiple constructors, or multiple methods with the same name, these appear sequentially, with no other code in between not even private members. Terminology Note: block-like construct refers to the body of a class, method or constructor. Note that, by Section 4. Braces are used with if , else , for , do and while statements, even when the body is empty or contains only a single statement.
Braces follow the Kernighan and Ritchie style " Egyptian brackets " for nonempty blocks and block-like constructs:. A few exceptions for enum classes are given in Section 4. Each time a new block or block-like construct is opened, the indent increases by two spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block. See the example in Section 4. Java code has a column limit of characters. A "character" means any Unicode code point. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in Section 4.
Each Unicode code point counts as one character, even if its display width is greater or less. For example, if using fullwidth characters , you may choose to wrap the line earlier than where this rule strictly requires. Terminology Note: When code that might otherwise legally occupy a single line is divided into multiple lines, this activity is called line-wrapping.
There is no comprehensive, deterministic formula showing exactly how to line-wrap in every situation.
Very often there are several valid ways to line-wrap the same piece of code. Note: While the typical reason for line-wrapping is to avoid overflowing the column limit, even code that would in fact fit within the column limit may be line-wrapped at the author's discretion. Tip: Extracting a method or local variable may solve the problem without the need to line-wrap. The prime directive of line-wrapping is: prefer to break at a higher syntactic level.
Note: The primary goal for line wrapping is to have clear code, not necessarily code that fits in the smallest number of lines. In general, two continuation lines use the same indentation level if and only if they begin with syntactically parallel elements. Section 4. A single blank line may also appear anywhere it improves readability, for example between statements to organize the code into logical subsections.
A blank line before the first member or initializer, or after the last member or initializer of the class, is neither encouraged nor discouraged. Beyond where required by the language or other style rules, and apart from literals, comments and Javadoc, a single ASCII space also appears in the following places only. This rule is never interpreted as requiring or forbidding additional space at the start or end of a line; it addresses only interior space. Terminology Note: Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.
This practice is permitted, but is never required by Google Style. It is not even required to maintain horizontal alignment in places where it was already used. Tip: Alignment can aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder perhaps you to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings.
That one-line change now has a "blast radius. Optional grouping parentheses are omitted only when author and reviewer agree that there is no reasonable chance the code will be misinterpreted without them, nor would they have made the code easier to read. It is not reasonable to assume that every reader has the entire Java operator precedence table memorized.
After each comma that follows an enum constant, a line break is optional. Additional blank lines usually just one are also allowed. This is one possibility:. An enum class with no methods and no documentation on its constants may optionally be formatted as if it were an array initializer see Section 4.
Every variable declaration field or local declares only one variable: declarations such as int a, b; are not used. Exception: Multiple variable declarations are acceptable in the header of a for loop. Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used within reason , to minimize their scope.
Local variable declarations typically have initializers, or are initialized immediately after declaration. Any array initializer may optionally be formatted as if it were a "block-like construct. The square brackets form a part of the type , not the variable: String args , not String args. Terminology Note: Inside the braces of a switch block are one or more statement groups. Each statement group consists of one or more switch labels either case FOO: or default: , followed by one or more statements or, for the last statement group, zero or more statements.
The following switch label returns to the previous indentation level, as if a block had been closed. Within a switch block, each statement group either terminates abruptly with a break , continue , return or thrown exception , or is marked with a comment to indicate that execution will or might continue into the next statement group. This special comment is not required in the last statement group of the switch block. Notice that no comment is needed after case 1: , only at the end of the statement group.
Each switch statement includes a default statement group, even if it contains no code. Exception: A switch statement for an enum type may omit the default statement group, if it includes explicit cases covering all possible values of that type. This enables IDEs or other static analysis tools to issue a warning if any cases were missed. Annotations applying to a class, method or constructor appear immediately after the documentation block, and each annotation is listed on a line of its own that is, one annotation per line.
These line breaks do not constitute line-wrapping Section 4. Exception: A single parameterless annotation may instead appear together with the first line of the signature, for example:.
Annotations applying to a field also appear immediately after the documentation block, but in this case, multiple annotations possibly parameterized may be listed on the same line; for example:. This section addresses implementation comments. Javadoc is addressed separately in Section 7, Javadoc. Any line break may be preceded by arbitrary whitespace followed by an implementation comment. Such a comment renders the line non-blank. Block comments are indented at the same level as the surrounding code.
Class and member modifiers, when present, appear in the order recommended by the Java Language Specification:. For example, L rather than l. Identifiers use only ASCII letters and digits, and, in a small number of cases noted below, underscores. In Google Style, special prefixes or suffixes are not used. Package names are all lowercase, with consecutive words simply concatenated together no underscores. Nested Classes and Interfaces 5. Static Nested Types 5. Static Nested Classes 5.
Nested Interfaces 5. Inner Classes 5. Accessing Enclosing Objects 5. Extending Inner Classes 5.
Inheritance, Scoping, and Hiding 5. Local Inner Classes 5. Inner Classes in Static Contexts 5. Anonymous Inner Classes 5. Inheriting Nested Types 5. Nesting in Interfaces 5. Modifiable Variables in Interfaces 5.
Implementation of Nested Types 6. Enumeration Types 6. A Simple Enum Example 6. Enum Declarations 6. Enum Modifiers 6. Enum Constant Declarations 6.
Construction 6. Constant Specific Behavior 6. Enum 6.
To Enum or Not 7. Tokens, Values, and Variables 7. Lexical Elements 7.
Character Set 7. Comments 7. Tokens 7. Identifiers 7. Keywords 7. Types and Literals 7. Reference Literals 7. Boolean Literals 7. Character Literals 7. Integer Literals 7. Floating-Point Literals 7. String Literals 7. Class Literals 7. Variables 7. Field and Local Variable Declarations 7. Parameter Variables 7. Array Variables 7. Array Modifiers 7. Arrays of Arrays 7. Array Initialization 7. Arrays and Types 7. The Meanings of Names 8. Primitives as Types 8. Common Fields and Methods 8. Construction 8. Constants 8. Common Methods 8. Void 8. Boolean 8.
The Integer Wrappers 8. The Floating-Point Wrapper Classes 8. Character 8. Working with UTF 8. Boxing Conversions 9. Operators and Expressions 9. Arithmetic Operations 9. Integer Arithmetic 9. Floating-Point Arithmetic 9. General Operators 9. Increment and Decrement Operators 9. Relational and Equality Operators 9. Logical Operators 9. Bit Manipulation Operators 9. The Conditional Operator?
Assignment Operators 9. String Concatenation Operator 9.
Expressions 9. Order of Evaluation 9. Expression Type 9. Type Conversions 9. Implicit Type Conversions 9. Explicit Type Casts 9. String Conversions 9. Operator Precedence and Associativity 9. Member Access 9. Finding the Right Method Control Flow Statements and Blocks Basic for Statement Enhanced for Statement Labels What, No goto? Generic Types Generic Type Declarations Bounded Type Parameters Nested Generic Types Working with Generic Types Subtyping and Wildcards Generic Methods and Constructors Generic Invocations and Type Inference Wildcard Capture Under the Hood: Erasure and Raw Types Erasure at Runtime Overloading and Overriding Finding the Right Method — Revisited Class Extension and Generic Types Exceptions and Assertions Creating Exception Types Transfer of Control Asynchronous Exceptions The throws Clause Exception Chaining Stack Traces When to Use Exceptions Assertions The assert Statement When to Use Assertions State Assertions Control Flow Assertions Turning Assertions On and Off Why Turn Assertions On and Off?
Controlling Assertions on the Command Line Complete Removal Making Assertions Required Strings and Regular Expressions Character Sequences The String Class Basic String Operations String Comparisons String Literals, Equivalence and Interning Making Related Strings String Conversions Strings and char Arrays Strings and byte Arrays Character Set Encoding Regular Expression Matching Regular Expressions Compiling and Matching with Regular Expressions Replacing Regions Efficiency The StringBuilder Class Modifying the Buffer Getting Data Out Capacity Management The StringBuffer Class Working with UTF Threads Creating Threads Using Runnable Synchronization Static synchronized Methods Synchronization Designs Details of Waiting and Notification Thread Scheduling Voluntary Rescheduling Deadlocks Ending Thread Execution Cancelling a Thread Waiting for a Thread to Complete Ending Application Execution The Memory Model: Synchronization and volatile Synchronization Actions Final Fields and Security The Happens-Before Relationship Thread Management, Security, and ThreadGroup Threads and Exceptions Don't stop ThreadLocal Variables Debugging Threads Annotations A Simple Annotation Example Annotation Types Annotating Elements Restricting Annotation Applicability Retention Policies Working with Annotations Reflection The Class Class Type Tokens Class Inspection Examining Class Members Naming Classes Obtaining Class Objects by Name Runtime Type Queries Annotation Queries The Modifier Class The Member classes Access Checking and AccessibleObject The Field Class Final Fields The Method Class Creating New Objects and the Constructor Class Inner Class Constructors Generic Type Inspection Type Variables Parameterized Types Wildcards Generic Arrays String Representations of Type Objects Arrays Genericity and Dynamic Arrays Packages The Proxy Class Loading Classes The ClassLoader Class Preparing a Class for Use Loading Related Resources Controlling Assertions at Runtime Garbage Collection and Memory Garbage Collection A Simple Model Finalization Resurrecting Objects during finalize Interacting with the Garbage Collector Reachability States and Reference Objects The Reference Class Strengths of Reference and Reachability Reference Queues Finalization and Reachability Package Naming Type Imports Package Access Accessibility and Overriding Methods Package Contents Package Annotations Package Objects and Specifications Documentation Comments The Anatomy of a Doc Comment Tags Inheriting Method Documentation Comments Inheriting throws Comments A Simple Example External Conventions Package and Overview Documentation The doc-files Directory Notes on Usage Streams Overview Byte Streams InputStream OutputStream Character Streams Reader Writer Character Streams and the Standard Streams