Java IndentationIn programming, indentation is just like formatting. It is used to make the code readable to other users because it makes the code easier to edit, displays how the braces match up, and shows the logic of the program in well-organized fashion. It signals to the reader that he/ she is about to dive into another a new section of a program. Generally, the unit of indentation is 4 spaces. Tabs expand to 8 spaces.
The goal of the indentation is to show the logic of the program. We must keep indentation throughout the program because it is an essential part of formatting. For statements inside a left and right brace, increase the indenting by two spaces. When another pair of braces is nested inside those braces, increase the indentation by another two spaces. It is a good impression to line up the braces vertically. Remember that the function of indentation is to make the program more readable and understandable that saves an immense amount of time when editing or refining the code. The braces used in Java follows the Kernighan and Ritchie style (K & R Style) to indent non-empty blocks and blocks like construct.
Let's consider the following code snippet. An empty block or block-like construct may be in K & R style. On the other hand, it may be closed immediately after it is opened, with no characters or line break in between ({}), unless it is part of a multi-block statement (like try/ catch, and finally). For examples, consider the following code snippet. Keep opening brace at the same line. Every next contained block needs to be indented, so it is easier to read when viewing the code. Remember that if we are building commercial software, each line of code is written once, but read 2 - 6 times, so we will do good to other people by properly formatting the code. Strring.indent() MethodJava also provides indent() method that provides the indentation for the strings based on the count value. It also normalizes line termination characters. Syntax: Where count denotes the number of white spaces to add or remove. Note that the value of count can be positive or negative. Positive value denotes adding space and negative value denotes removing space. It automatically adds a newline character if it hasn't been provided yet.
IndentExample.java Output: Next TopicZig Zag Star and Number Pattern in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India