Indentation and Formatting
Indentation and formatting refer to how the code is structured visually using spaces, tabs, and line breaks. While it doesn't affect how the code runs, it greatly enhances readability and maintainability.
Why it's Important
- Helps developers understand the logic flow quickly.
- Makes debugging and reviewing easier.
- Avoids confusion in nested structures like loops, if-else, and methods.
- Professional and collaborative coding requires consistent formatting.
Note :
The Java compiler ignores indentation and white spaces, but following a consistent formatting style is considered a good programming practice.
However, in Python, indentation is not just for readability — it's part of the language syntax itself.
Example: Properly Indented Code
public class Example {
public static void main(String[] args) {
int x = 10;
if (x > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}
}
}
Bad Formatting Example (Avoid this)
public class Example{
public static void main(String[] args){
int x=10;
if(x>0){
System.out.println("Positive");
}else{
System.out.println("Non-positive");}}
}
Best Practices
- Use braces { } even for single-line blocks to prevent bugs.
- Keep line length within 80–100 characters.
- Add space after keywords like
if,for,while, etc. - Use blank lines to separate logical blocks of code.
Summary
- Indentation doesn't affect program execution but improves code readability.
- It makes debugging, collaboration, and maintenance easier.
- Always use consistent formatting throughout the program.
- In Java — indentation is for humans.
In Python — it's mandatory for both humans and the interpreter.