728x90 AdSpace

Saturday, 14 September 2013

Java Best Practice - Declarations

Number Per Line
int level; // indentation level

int size; // size of table
is prepared over
int level, size;
Do not put different type on the same line. Example:
int foo, fooarray[]; //WRONG
Note: The example above use one space between the type and the identifier. Another acceptable alternative is to use tabs, example:
int          level;             // indentation level

int size; // size of table

Object currentEntry; // currently selected table entry
Try to initialize local variable where they are declared. The only reason to initialize a variable where it’s declared is if the initial value depends on some computation occurring first.

Put declaration only at beginning of blocks.(A block is any code surround by curly braces “{” and “}” ) Don’t wait to declare variables until their first use, it can confuse the unwary programmer and hamper code portability within the scope.
void methodName() {

int var1 = 0; //beginning of method block

if (condition) {

int var2 = 0; //beginning of “if” block



The one exception to the rule is indexes of for loops, which in Java can be declared in the for statement:
for(int i = 0; i < maxLoops; i++) { … }
Avoid local declarations that hides declarations at higher levels. For example, do not declare the same variable name  at inner block.
int count;


myMethod() {

if (condition) {

int count; //AVOID


Class and Interface Declaration
When coding Java classes and interfaces, the following formatting rules should be followed:
  1. No space between method name and parenthesis “(” starting its parameter list

  2. Open brace “{” appears at the end of same line as the declaration statement

  3. Closing brace “}”  starts a line by itself indented to match its corresponding opening statement, except when it is null statement the “}” should appear immediately after the “{”
class Example extends Object {

int var1;

int var2;

Example(int i, int j){

var1 = i;

var2 = j;


int emptyMethod() {}


5.Method are separated by a blank line
Annamalai Thangaraj

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments


Post a Comment

Item Reviewed: Java Best Practice - Declarations Rating: 5 Reviewed By: Annamalai Thangaraj