// правильно
if (true) {
// неправильно
if (true)
{
// правильно
while (true) {
// some code
// неправильно
while (true) { // some code
// правильно
for (true) {
// some code
}
// неправильно
while (true) { /* some code */ }
// неправильно
if (true) {
/* some code */ }
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);
}
}
}; // Приемлемо
void doNothing() {}
// Также приемлемо
void doNothingElse() {
}
// Неприемлемо: нельзя использовать пустые блоки в многоблочных операторах
try {
doSomething();
} catch (Exception e) {} MyLambda<String, Long, Object> lambda =
(String label, Long value, Object obj) -> {
...
};
Predicate<String> predicate = str ->
longExpressionInvolving(str);
switch (x) {
case ColorPoint(Color color, Point(int x, int y)) ->
handleColorPoint(color, x, y);
...
} private int x; // хорошо
private Color color; // и это тоже
private int x; // разрешено, но при редактировании в будущем
private Color color; // можно оставить без выравнивания private enum Answer {
YES {
@Override public String toString() {
return "yes";
}
},
NO,
MAYBE
} private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS } new int[] {
0, 1, 2, 3
}
new int[] {
0, 1,
2, 3
}
new int[]
{0, 1, 2, 3}
new int[] {
0,
1,
2,
3
} switch (number) {
case 0, 1 -> handleZeroOrOne();
case 2 ->
handleTwoWithAnExtremelyLongMethodCallThatWouldNotFitOnTheSameLine();
default -> {
logger.atInfo().log("Surprising number %s", number);
handleSurprisingNumber(number);
}
} switch (input) {
case 1:
case 2:
prepareOneOrTwo();
// fall through
case 3:
handleOneTwoOrThree();
break;
default:
handleLargeNumber(input);
} return switch (list.size()) {
case 0 -> "";
case 1 -> list.getFirst();
default -> String.join(", ", list);
}; final @Nullable String name;
public @Nullable Person getPersonByName(String name); /** Класс. */
@Deprecated
@CheckReturnValue
public final class Frozzler { ... }
/** Пакет. */
@Deprecated
@CheckReturnValue
package com.example.frozzler;
/** Модуль. */
@Deprecated
@SuppressWarnings("CheckReturnValue")
module com.example.frozzler { ... } @Deprecated
@Override
public String getNameIfPresent() { ... } @Override public int hashCode() { ... } @Partial @Mock DataLoader loader; /*
* This is // And so /* Or you can
* okay. // is this. * even do this. */
*/ // TODO: crbug.com/12345678 - Удалите после окончания срока действия совместимости с версией 2047q4. // TODO: @ваше_имя_пользователя - Создайте заявку и используйте '*' для повтора. public protected private abstract default static final sealed
non-sealed transient volatile synchronized native strictfp transitive static // Константы
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final Map<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
static final Joiner COMMA_JOINER = Joiner.on(','); // поскольку Joiner неизменяем
static final SomeMutableType[] EMPTY_ARRAY = {};
// Не константы
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final ImmutableMap<String, SomeMutableType> mutableValues =
ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"}; try {
int i = Integer.parseInt(response);
return handleNumericResponse(i);
} catch (NumberFormatException ok) {
// Это не число; это нормально, просто продолжаем
}
return handleTextResponse(response); Foo aFoo = ...;
Foo.aStaticMethod(); // правильно
aFoo.aStaticMethod(); // неправильно
somethingThatYieldsAFoo().aStaticMethod(); // неправильно /**
* Многострочный текст Javadoc пишется здесь,
* с обычным переносом строк...
*/
public int method(String p1) { ... } /** Особенно короткий текст Javadoc. */