Skip to main content

Java Std Coding


The objective of this document is to address the conventions required for packages written in Java
      -              to avoid most common errors
      -              to make code maintainable
      -              to make code readable

It also tries to address some of the issues involved in designing and programming in Java.  This is by no means a final word on these issues.


Package Names

i. Package name should be in all lower case. The initial package name representing the domain name must be in lower case.

e.g.   package;

File Names

i.    The Java files must have .java extension.


File name:

Ccccccccc - Meaningful class name

The last few letters are to be used for describing file functionality. Use uppercase for the first letter of the functionality as well as for the first letter.

e.g.    // Editor   Copy
          // Graph    Zoom
         // NODE     Connect
       // SB       Credit


i. Names representing types must be nouns and written in mixed case starting with upper case. Common practice in the Java development community and also the type naming convention used by Sun for the Java core packages
                Eg.          Line, AudioSystem.         


Constants should be written in upper case letters only. Underscore can be used to separate meaningful words. The names should be self- explanatory. Write comments if the names are not self explanatory.

Eg..        int   final LOGIN_SUCCESS = 1;

Associated constants (final variables) should be prefixed by a common type name.

Eg.             final int COLOR_RED = 1;
                   final int COLOR_GREEN = 2;
                   final int COLOR_BLUE = 3;

Class Names

Main class must be the same as the file name. The class name must start with uppercase and the first letter of the next word should be capitalized.

                Eg.          : GrZoom.class

One file can contain only one public class. But this class can have private helper classes defined in the same file. To other members of the package in which the class belongs, only the public class will be available. The names of these private classes should be appropriately named.

Exception classes should be suffixed with Exception.

Eg.                         class AccessException extends Exception   {

Singleton classes should return their sole instance through method getInstance

Eg.             class UnitManager  {
    private final static UnitManager instance_ = new UnitManager();
    private UnitManager()    {
   public static UnitManager getInstance()           
  instance() or unitManager() etc.   {
   return instance_;

Method Names

For all methods, start the method name with lowercase and the keyword to start with uppercase (Hungarian Notation)

                Eg.                          toString();

The main points to be considered for naming a method are

 (1) Return type   and   (2) Functionality.

The method name can be divided into two parts: Prefix (describing the return type) and Functionality.

From the prefix one should be able to know the return type without any difficulty. This will reduce bugs that occur due to assignment of the return value to a variable of different type.

A typical method name will look like these:

intGetValues (...);
                // returns int

longAccountNumber (...) ;
                // returns a long ;

If the method returns a user defined type, a suitable prefix of max. 4 and min. 2 characters has to be used. The first letter has to be in upper case.
Eg.          .               PlnFitPlane(...) ;                // Pln is for class Plane

·         This Prefix need not be used if the method has a name which describes the return value
Eg.                          :toString(); toInt();

The name of the object is implicit, and should be avoided in a method name.

 Eg.         line.intGetLength(); // NOT: line.intGetLineLength();

The terms get/set must be used where an attribute is accessed directly

Eg.            employee.intSetName(name);
     matrix.intGetElement(2, 4);
     matrix.intSetElement(2, 4, value);

The term compute can be used in methods where something is computed.

Eg.          valueSet.intComputeAverage();

The term find can be used in methods where something is looked up.

Eg.       vertex.longFindNearestVertex();
 node.charFindShortestPath(Node destinationNode);

The term initialize can be used where an object or a concept is established.

Eg.          printer.initializeFontSet();

JFC (Java Swing) variables should be suffixed by the element type.

Eg.      widthScale,

Prefixes for Programmer Defined Names

Use the prefixes and guidelines recommended below for constructing programmer defined names.

The Hungarian notation is to be followed for naming variables.

A consistent naming convention makes code easier to read, understand, debug and maintain.


         Arrays should always be specified using the form and the maximum length of the array name is 30                      characters.

         <data type>[][]…[] arrayname;
               Eg..     int [] companyNames;
                     double [][] salary;

         The form given below must NOT be used:
       Eg.       int myArray [];  //WRONG USAGE!

EJB Class and Interface Names

The classes and interfaces for EJBs should follow the following conventions in places wherever applicable.

The bean name should follow the same conventions as like class names. If the Enterprise bean to be created is Xyz, then

  •                 the Bean class should be named as XyzBean,
  •                 the Home interface should be named as XyzHome and
  •                 the Remote interface should be named as Xyz.

          For an entity bean the key class should be names as XyzKey.
  If the bean to be created is CustomerAccount then the naming convention is as follows:

       Bean class                                            : CustomerAccountBean
       Home Interface                                 : CustomerAccountHome
       Remote Interface                                             : CustomerAccount
       Key class (in case of entity bean)               : CustomerAccounKey

Vector and Hashtable

      Vector and Hashtable names should end with an “s” to represent multiplicity of elements as far as   possible.

Use of Upper Case to Delimit Parts of a Name

Each variable name should have two parts:
·         a suitable prefix and
·         a meaningful name

All global variables must be prefixed with the letter ‘g’. The order to be followed while naming global variables is

<scope><datatype prefix><Variable name>

Eg..        private int giAmount = 0;

A name may consist of different parts; 

e.g. txtCustName. Start each part of a name with an upper case character.

Makes code easier to read, understand, debug and maintain.

Use of Meaningful Names

·         Programmer defined names should be functionally meaningful, and should indicate the purpose of the variable/control/method in question.

·         Avoid cryptic names, even in case of scratch pad variables or counters.

·         Bad or cryptic names waste programmer effort. Time is spent in just understanding the role of the variable/control/method rather than in understanding functionality or solving a problem.

·         Complement names must be used for complement entities 

Eg. get/set, add/remove, create/destroy, start/stop, insert/delete, increment/decrement, old/new, begin/end, first/last, up/down, min/max, next/previous, old/new, open/close, show/hide, suspend/resume, etc.

  • Abbreviations in names should be avoided
Eg.    computeAverage();                       // NOT: compAvg();
  ActionEvent event;                        // NOT: ActionEvent e;
catch (Exception exception) {      // NOT: catch (Exception e) {

·          Abbreviations and Acronyms

Eg.:    exportHtmlSource();                      // NOT: exportHTMLSource();
                openDvdPlayer();                            // NOT: openDVDPlayer();

Using all uppercase for the base name will give conflicts with the naming conventions given above. A variable of this type would have to be named DVD, HTML etc. which obviously is not very readable. Another problem is illustrated in the examples above; When the name is connected to another, the readability is seriously reduced; The word following the acronym does not stand out as it should.


Length of Names

Identifiers must be as short as possible without obscuring their meaning, preferably 20 characters or less. Unambiguous abbreviations should be used wherever possible. For example, use txtCustName instead of txtCustomerName.

Excessively long variable names are cumbersome and irritating for programmers to use, hence chances of error during coding are higher.

Variable Names

  The following prefixes should be used while naming the variables:

Variables of Primitive Data Types

Data Type

  • is prefix should be used for boolean variables and methods
Eg.          isSet, isVisible, isFinished, isFound, isOpen

  • Negated boolean variable names must be avoided.
Eg.          bool isError;                                       // NOT: isNoError
bool isFound;                                     // NOT: isNotFound

Variables of Wrapper Class Data Types

Variable datatype
(Local variables)
(Global variables)

Plural form should be used on names representing a collection of objects.

Eg.          Collection<Point> points;
int[] values;

n prefix should be used for variables representing a number of objects.

Eg.       nPoints, nLines

Naming of Controls

Check box
List box
Text Field
Grid Layout
GridBag Layout
Flow Layout
Border Layout

Naming of Classes extending Standard Java classes

          Base class

Naming of Private Class Variables

i. Private class variables should have underscore suffix.

 Eg.      class Person {
   private String name_;

Naming of GenericVariables

i. Generic variables should have the same name as their type.
      Eg.    void setTopic(Topic topic)                             // NOT: void setTopic(Topic value)
                                                                // NOT: void setTopic(Topic aTopic)
                                                                 // NOT: void setTopic(Topic t)
                void connect(Database database)           // NOT: void connect(Database db)
                                                                                // NOT: void connect(Database oracleDB)

File Organization

A file consists of sections that should be separated by blank lines and optional comments identifying each section.

Java Source Files

i. Java source files should have the extension .java.
ii. File content must be kept within 80 columns.

             80 columns is the common dimension for editors, terminal emulators, printers and debuggers,             and files that are shared between several developers should keep within these constraints. It improves readability when unintentional line breaks are avoided when passing a file between programmers
iii. Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, these can be put in the same source file as the public class. The public class should be the first class or interface in the file.
Java source files should have the following ordering

·         Beginning Comments
·         Package and import statements
·         Class and interface declarations
          ·         Class (static) variables. The order of these variables should be public, protected and                              then private
·         Instance variables. The order of these variables should be public, protected and then            private
·         Constructors
·         Methods - These should be grouped by functionality.


Package and Import Statement

·         The package statement must be the first statement of the file. All files should belong to a specific package.
·         Two Imported classes should always be listed explicitly.

Eg.                 import java.util.List;                       // NOT: import java.util.*;
                      import java.util.ArrayList;
                      import java.util.HashSet;

Class and Interfaces

  • Class and Interface declarations should be organized in the following manner:
1.       Class/Interface documentation.
2.       Class or interface statement.
3.       Class (static) variables in the order public, protected, package (no access modifier),            private.
4.       Instance variables in the order public, protected, package (no access modifier), private.
5.       Constructors.
6.       Methods (no specific order).


  • Methods Modifiers should be given in the following order
<access> static abstract synchronized <unusual> final native

The <access> modifier (if present) must be the first modifier.

               Eg.           public static double square(double a);   // NOT: static public double                                                       square(double a);


  • Type conversions must always be done explicitly. Never rely on implicit type conversion.
Eg.          floatValue = (int) intValue;                          // NOT: floatValue = intValue;

Array specifiers must be attached to the type not the variable.

Eg.   int[] a = new int[20];                                       // NOT: int a[] = new int[20]


  • Variables should be initialized where they are declared and they should be declared in the smallest scope possible.
  • This ensures that variables are valid at any time. Sometimes it is impossible to initialize a variable to a valid value where it is declared. In these cases it should be left uninitialized rather than initialized to some phony value.
  • Class variables should never be declared public
The concept of Java information hiding and encapsulation is violated by public variables. Use private variables and access functions instead. One exception to this rule is when the class is essentially a data structure, with no behavior (equivalent to a C++ struct). In this case it is appropriate to make the class' instance variables public

  • Arrays should be declared with their brackets next to the type
Eg.   double[] vertex;                                   // NOT: double vertex[];
int[] count;                              // NOT: int count[];
public static void main(String[] arguments)
public double[] computeVertex()
  • Variables should be kept alive for as short a time as possible
Keeping the operations on a variable within a small scope, it is easier to control the effects and side effects of the variable.


  • Only loop control statements must be included in the for() construction.

Eg.   sum = 0;                                  // NOT: for (i = 0, sum = 0; i < 100; i++)
                  for (i = 0; i < 100; i++)
                  sum += value[i];
        sum += value[i];

  • The use of do-while loops can be avoided.

do-while loops are less readable than ordinary while loops and for loops since the conditional is at the bottom of the loop. The reader must scan the entire loop in order to understand the scope of the loop.
In addition, do-while loops are not needed. Any do-while loop can easily be rewritten into a while loop or a for loop. Reducing the number of constructs used enhance readbility.
  • The use of break and continue in loops should be avoided


·        Complex conditional expressions must be avoided. Introduce temporary boolean variables instead

Eg       bool isFinished = (elementNo < 0) || (elementNo > maxElement);
 bool isRepeatedEntry = elementNo == lastElement;
                                if (isFinished || isRepeatedEntry)
                                // NOT:
              if((elementNo<0)||elementNo>maxElement)||elementNo== lastElement)

  • The conditional should be put on a separate line.

  Egif (isDone)                            // NOT: if (isDone) doCleanup();

  • Executable statements in conditionals must be avoided.

  Eg.  InputStream stream =, "w");
 if (stream != null) {
// NOT:
if (, "w") != null)) {

Conditionals with executable statements are simply very difficult to read. This is especially true for programmers new to Java.


  • The use of magic numbers in the code should be avoided. Numbers other than 0 and 1can be considered declared as named constants instead.

The use of magic numbers in the code should be avoided. Numbers other than 0 and 1can be considered declared as named constants instead.
Eg.          private static final int TEAM_SIZE = 11;
Player[] players = new Player[TEAM_SIZE];          // NOT: Player[] players = new Player[11];
If the number does not have an obvious meaning by itself, the readability is enhanced by introducing a named constant instead.

  • Floating point constants should always be written with decimal point and at least one decimal.

Eg.   double total = 0.0;                           // NOT: double total = 0;
double speed = 3.0e8;                    // NOT: double speed = 3e8;
                double sum;
                sum = (a + b) * 10.0;

  • Floating point constants should always be written with a digit before the decimal point.

Eg.   double total = 0.5;                           // NOT: double total = .5;


·         The class and interface declarations should have the following form:

Eg.       class Rectangle extends Shape
implements Cloneable, Serializable

This follows from the general block rule above. Note that it is common in the Java developer community to have the opening bracket at the end of the line of the class keyword. This is not recommended.
·         Method definitions should have the following form:

Eg.          public void someMethod()
throws SomeException

·         White Space
Operator should be surrounded by a space character
Java reserved words should be followed by a white space
Commas should be followed by a space character
Colon should be surrounded by a space character
Semicolon in for statement should be followed by a white space

Eg   a = (b + c) * d;                                    // NOT: a=(b+c)*d
while (true) {                            // NOT: while(true){
doSomething(a, b, c, d);          // NOT: doSomething(a,b,c,d);
            case 100 :                                // NOT: case 100:
            for (i = 0; i < 10; i++)
// NOT: for(i=0;i<10;i++)

·         Method names can be followed by a white space when it is followed by another name.
doSomething (currentFile);
·         Logical units within a block should be separated by one blank line.

Eg.       // Create a new identity matrix
Matrix4x4 matrix = new Matrix4x4();

// Precompute angles for efficiency
double cosAngle = Math.cos(angle);
double sinAngle = Math.sin(angle);

// Specify matrix as a rotation transformation
matrix.setElement(1, 1, cosAngle);
matrix.setElement(1, 2, sinAngle);
matrix.setElement(2, 1, -sinAngle);
matrix.setElement(2, 2, cosAngle);

// Apply rotation

·         Variables in declarations can be left aligned.

Eg.   TextFile file;
int nPoints;
double x, y;


Write neat, readable and meaningful comments. Use the javadoc format of  /**  Comments */. This enables a documentation of the class in HTML format to be carried out by running the javadoc documentation tool provided by JDK. Note that the javadoc generates documentation only for variables and methods with public, protected or private protected access. Any comments relating to private or default package variables and methods are not translated to the output documentation. This is in keeping with the object oriented methodology where only what is accessible to other classes should be revealed. Please refer appendix 1for more details on documentation using javadoc

Comments for a Class    

Following should be incorporated just above the class definition

                i.              Author:

                ii.             Functionality description:
                                What it is supposed to do. Any algorithms used or books referred.

                iv.           External Methods Called:

                v.            Known Bugs and/or side effects:
                                These are added during testing or if some decision has to taken during coding that you foresee to cause problems.

                vi.           Start Date:

vii.                Modification log :

Just above a method explain the following
                i.              Brief Description of the method

                ii.             Explain return values

                iii.            Parameters:
                                All parameters must have explanation.

                iv.           Pseudocode:
                                It is a good practice to write the Pseudo code before the actual coding starts.

The functionality of each method in the code must be written in the given format at the beginning of the method.

Single Line Comments

Use the ‘//’ comment delimiter to put in single line comments. A blank line should precede a single line comment. The format is given below.

<Your code>
<Blank line>
// Your comment
<Your code>

 Eg.        iCount = iCount + 1;

             //Checking if iCount is less than max count
  if (iCount == I_MAX)

Block Comments

A block comment should be preceded by a blank line to set it apart from the rest of the code. Block comments should be formatted as follows

 * This is a block comment

         It is a general practice to highlight the comment inside the source file as shown above. Since javadoc  treats the first line as /** followed by many asterisks (NOT /* followed by asterisks), this box structure is treated as a documentation comment. This will appear in the javadoc output and will result in very bad user documentation. AVOID USING “BOX” - ING for multi-line comments.

End of Line Comments

Use the //comment delimiter to put in comments at the end of a line. This should not be used to comment out  multiple lines of code.

Comments for modified code

If a section of code has been modified due to requirement change, always consider modification of code as removal of older code and addition of the new code. The older code should not be deleted. Instead it must be commented as described below. Similarly follow the method given in this section while adding new code.

Modification of code

If a section of code has to be modified the following convention should be followed.

//++ <CR NAME>
// <Code commented>
<Code added>
//-- <CR NAME>

Eg:          //++ CR2034
// fTemperature = 12.3;
fTemperature = 14.6;
//-- CR2034

Note: If CR NAME not available, an internally generated number (with reference to CMPLAN) such as RMnnn where nnn starts from 001 upto 999 can be used.

Eg.                                RM001

Addition of code

The following convention should be followed if a section code has to be added.
                Multiple lines of code added

// ++ <CR NAME>
Section of code added
// -- <CR NAME>

Eg.          // ++ CR 4567
private String gstrPropertyFile = new String();
private String gstrPartner = new String();
// -- CR 4567

Single line of code added

<Code added> //++ <CR NAME> –

Eg:          iAmount = 1000;               //++ CR1042 --

Note: If CR NAME not available, an internally generated number (with reference to CMPLAN) such as RMnnn where nnn starts from 001 upto 999, can be used.

Eg.                          RM001

Removal of code

The following convention should be followed if a section of code has to be removed.

      Removal of multiple lines of code

// ++ <CR NAME>
Section of code to be removed
// -- <CR NAME>

Eg.          // ++ CR 4567
// Exception handling
private Hashtable ghtbException = new Hashtable();
private String gstrException = new String();
// -- CR4567

      Removal of a single line of code

      //<Code to be removed>              //++ <CR NAME> --

Eg.          // iCount = 2;     //++ CR 9456 –

Note: If CR NAME not available, an internally generated number (with reference to CMPLAN) such as RMnnn where nnn starts from 001 upto 999 can be used.

Eg.                          RM001


The style followed must be readable. Be consistent. The same style has to be followed through out the class and application. Here are two different styles of coding

                void  vectMyFn (...){


                vectMyFn (...)


Both the styles are can be used, but be consistent.

Whatever the convention is followed, the code must be aligned properly. Use the same tab size for all the files.

Line Length

Avoid line longer than 70 characters as readability becomes an issue.

Wrapping Lines

When an expression will not fit on a single line, break it according to these general principles
·         Break after a comma
·         Break before an operator
·         Align the new line with the beginning of the expression at the same level on the previous line
·         If the above rules lead to confusing code, just indent 8 spaces instead.

Eg.                Method1(longExpression1, longExpression2, longExpression3,
                LongExpression4, longExpression5);
Var2 = longName1 + longName2 – longName3 * (longName4 +


Each block should start in a new line and the opening brace should be there in the starting line of the block itself.

         Eg.       try    {
                                                 . . . .
                                                } catch (arg0 e0) {
                                                        . . . .
                                                } catch (arg1 e1) {
                                                 . . . .
                                                 } finally {
                                                                . . . .



We should almost never be writing functions that declare themselves to throw Exception. This makes it very difficult to code to an API and handle Exceptions gracefully. Throw the particular Exception sub-class that is appropriate to your code—either one of the pre-existing java Exceptions or your own.

Catch() Statement

Here are some Best Practices for your catch statements.

In general, no one should catch( Throwable ). Throwable has 2 sub-classes, Error and Exception. Errors are Really Bad Things that often indicate VM-wide problems, such as OutOfMemoryError. Generally speaking, no one wants to catch these in their applications.  If you catch( Throwable ) and the Throwable is an instanceof ThreadDeath and you don’t re-throw it, the Thread isn’t killed and Bad Things Happen.

In general, there is no reason to catch( Exception ). There are 2 types of Exceptions that can be thrown in any try block: checked Exceptions and unchecked Exceptions.  Checked Exceptions: These are the Exceptions declared in the throws clauses of the methods called in the try block. Because these Exceptions are declared, you know the types of Exceptions that can be thrown. The specific Exceptions you are after can each be caught independently.

The unchecked Exceptions are all sub-classes of RuntimeException. If you want to handle these, just catch( RuntimeException ). If you want to handle one or two specific RuntimeExceptions (the common one seems to be NullPointerException) just catch and handle that.

The avoidance of catch( Exception ) is more of a guideline. If, for example, you are going to catch a half-dozen different kinds of Exceptions and handle them all the same way, catch( Exception ) may make for cleaner code. Just be sure you are not masking problems when you do so.

 Eg.                         try
catch( FooException fooexc )
                // Do nothing
catch( BarException barexc )
                handleBar( barexc );

Empty Catch Blocks()

There should be no empty catch blocks, all exceptions should at minimum be logged

In the following piece of code,

Eg.                          try
                 // whatever
catch( Exception exc )
                // logging code


Usually all exceptions, errors and anomalous conditions of concern - in short any message that need attention - needs to be logged.

§  log4j is to be used for logging.
There are five levels of logging: FATAL, ERROR, WARN, INFO, and DEBUG.  Messages should be logged using an appropriate logging level as described below:

·         The DEBUG priority designates fine-grained informational events that are most useful to debug an application.  DEBUG messages should also be added for method entry and exit from any non-trivial methods.

·         The INFO level designates informational messages that highlight the progress of the application at coarse-grained level.  INFO messages should pertain to information that would be useful at a very high level.  Since these messages typically will be logged in the production environment, INFO messages should be used sparingly.  One example of an INFO message is that a user logged into the system.

·         The WARN level designates potentially harmful situations. 

·         The ERROR level designates error events that might still allow the application to continue running.

·         The FATAL level designates very severe error events that will presumably lead the application to abort.

Note : DEBUG will be turned off in production. INFO should be used only when you need to print essential information in the logs.
Always use ERROR for logging any Error messages and stack traces.

String vs StringBuffers

Instead of:
String strBig = “somestring”;
strBig += computeSomeOtherString();
strBig += “this”;
strBig += yetAnotherString();
String strBig = new StringBuffer( “somestring” ).append(
computeSomeOtherString()).append( “this” ).append(

You’ll be amazed how much faster your code runs if you are manipulating lots of strings.

JDBC Statement

If you use JDBC anywhere in your code, make sure you read & follow the procedures below.

Utilize Connection Pooling Techniques  : Any connection opened must be closed.  If connections are not closed they will not be released back to the database or to the connection pool. Use a connection pooling framework provided by Apache or your Appserver and don’t open and manage connections in your code.

Be diligent about closing all JDBC objects : Connections,ResultSets,Statements etc should always be closed to avoid “Too many Open Cursors” error in the database.
Use the “Finally” block to close all the JDBC objects
This is very important

Separate JDBC Code from Business Logic.  : Use a DataAccess framework or if not possible , create a simple Utility for all DB related activities. Do no speard the JDBC code everywhere in your classes !

Consider query fetch size for large result sets. : ResultSets are open cursors . They cannot be serialized or stored. Specify the size of retrieval when you are retrieving large resultsets.

Do not prepare Statements in a loop. If the statement needs to be executed in the loop, prepare it outside of the loop and parameterize and execute it inside the loop.
Close all the statements before next use and after the last use.

Boolean Objects

There is no need for having a java.lang.Boolean objects. There can only be 2 values for such objects, and they exist as static objects in the VM—Boolean.TRUE and Boolean.FALSE. It is recommended to use them.


If you have an entire method that needs to be called synchronously, the best way to guarantee that is with this syntax:

Eg.          class Good
                                public synchronized void someMethod()
                  // whatever

This syntax is basically shorthand for:

      Eg.        class OverlyIndented

                                           public void someMethod()
                                                      synchronized( this )
                                                       // whatever

Classes OverlyIndented and Good do the same thing & have the same synchronization, but class OverlyIndented is overly indented.

Note that synchronization should be done as locally as possible to where it is needed and should not be required of API users. Thus, this syntax is wrong:

Egclass Bad
                              *  Usage: abcd. Calls must be synchronized.

              public void someMethod()
                                           // whatever
                              Bad bad = new Bad();
synchronized( bad )


The problem with the Bad class is that it requires users of the API to know that synchronization is necessary. Instead, use the syntax as in the Good class below. However, note that, under some circumstances code like this may be correct:

Eg.   class Good
    public synchronized void goodMethod()
        // whatever

    public synchronized void betterMethod()
        // whatever

    public synchronized void bestMethod()
        // whatever

Good good = new Good();
synchronized( good )

Enumeration \iterations

There are a number of pieces of code where developers need to iterate through 2 same-sized vectors simultaneously and they do it using an enumeration for one and an int iterator for the other:

Vector vecOne = someVectorWithNElements;
Vector vecTwo = someOtherVectorWithNElements;
int intCount;
Enumeration enum;

intCount = 0;
for( enum = vecOne.elements(); enum.hasMoreElements();;)
    // do some stuff with v1 by calling enum.nextElement()
    // do some stuff with v2 by calling vecTwo.elementAt( intCount )
    intCount++;  // <-- To keep the iterator in sync with the enumerator

While this code will work, it is really bad style. If you want to walk through 2 different Vectors simultaneously, use one iterator for both of them:

Vector vecOne = someVector;
Vector vecTwo = someOtherVector;
int intCount;
int intSize;

intSize = vecOne.size();

for( intCount = 0; intCount < intSize; ++ intCount )
  // do some stuff with vecOne by calling vecOne.elementAt( intCount )
  // do some stuff with vecTwo by calling vecTwo.elementAt( intCount )



Class Size

The number of non-static methods should not exceed 20 for a Key class but on an average should be around 12. The number of non-static methods should not exceed 40 for a UserInterface class but on an average should   be around 25.
The number of static methods should not exceed 4 for a class;
Multiple classes of this size are more desirable and enable efficient debugging when compared to large classes. By following an object-oriented approach this should be implemented.

Method Size

The size of a method ideally should not cross 20 to 25 statements; the number of method calls  within a method should not exceed 7 to 9.


Number Per Line

One declaration per line is recommended since it encourages commenting.

Eg.   String strName ;//Name of Person
            String strType; // Type of Participant


Put declarations only at the beginning of blocks. Don’t wait to declare variables before their first use; it can lead to confusion

Initialising Variables

Java initializes the standard data type variables (int, char, boolean, float etc) that are declared outside methods. But all classes that have the Object class to be the parent are initialized to null. So care must be taken to initialize these variables first. For example when an instance of a String, or instance of a Vector or Hashtable are used. They must be initialized.

                                                Eg.          String strName= new String();



All classes of an application should belong to atleast one package.


Providing Access to Instance and Class Variables

Don’t make any instance or class variable public without good reason. Often, instance variables don’t need to be explicitly set or gotten—often that happens as a side effect of method calls.

One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it’s appropriate to make the class’s instance variables public.

Access Specifiers for a class

 Classes can be friendly (default), protected or public as the need may be· Use private if the method is accessible only within the class· Use friendly if the method is accessible only within the class and other classes within the same package· Use protected if the method is accessible only within the class, other classes within the same package and sub classes in different packages· Use public only if the method can be called from any class in any package.

Referring to Class Variables and Methods

Avoid using an object to access  static variables or methods. Use the class name instead.

Eg.       classMethod(); //OK
AClass.classMethod(); //OK
anObject.classMethod(); //AVOID!


Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values.

Variable Assignments

Avoid assigning several variables to the same value in a single statement. It is hard to read.

Eg.       fooBar.fChar = barFoo.lchar = 'c'; // AVOID!

Do not use the assignment operator in a place where it can be easily confused with the equalityoperator.

Eg.          if (c++ = d++) { // AVOID! Java disallows
should be written as
if ((c++ = d++) != 0) {

Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler, and besides, it rarely actually helps.

Eg.       d = (a = b + c) + r; // AVOID!
should be written as
a = b + c;
d = a + r;

Null checks

There should be null checks before you call any operation on a object

Eg.            myArrayList = dao.getDataList()
If (myArrayList != null )
….. Do the operation
Ex – myArrayList.size();
- myArrayList.getXYZ();

Hard-coding of string values in the source files

There should not be any hard coding in the java source files. All the constant strings/numeric values should be taken from the constant files.
Constant files are present at the application level – common/util (BE) and common (FE).
Module specific constant files will be created under the util packages within the respective FE and BE packages of the module.

Eg .         sca_fe/ pricingbenchmark/ util
sca_be/ services/ pricingbenchmark/ util

String comparison

Please use following order while doing string comparison

If ( “STRING_CONSTANT”.equals(dto.getPlanName())
// do something

Do not attempt to compare strings using code as:

If( “STRING_CONSTANT” == dto.getPlanName())
// do something

Object instantiation

If you have a for loop, to iterate on the list, define the object reference outside the loop and assign the new reference to same variable in for loop

Eg.                          Object obj = null;
for ( int i=0; i < araylist.size(); i++ )
obj = (Object)arrylist.get(i)

Do not instantiate object if it is not necessary in declaration

Eg.                           MyObject myObject = new MyObject()
myObject = dao.getObject()

In above code first object instantiation is unnecessary as the dao method will return you an object of type MyObject. However, null checking is a must before invoking any method on an object where the state of the object is undeterminable, in other words when the object creation scope is outside of your class logic.

Unnecessary method calls

In case where you have a for loop for traversing on an arraylist containing dto’s, most people have code like:

Eg.                          Arraylist al = proxy.getPlans(xyz);
for ( int i=0; i < al.size() ; i++ )
obj = (Object)al.get(i)

The code above leads to the invocation of size() method on the arraylist evertime the loop is executed.

This code can be re-written as:

Eg.                          Arraylist al = proxy.getPlans(xyz);
If(al != null)
int size = al.size();
for ( int i=0; i <size ; i++ )
obj = (Object)al.get(i)

However, this should not be done in case the ArrayList object is being altered inside the loop as the size obtained earlier will be incorrect.

String concatenation

In cases where String objects have to be altered, say 2 strings have to be appended to create a 3rd string, following code has been observed:

Eg.                          String s1 = “abc”;
String s2 = “xyz”;
String s3 = s1+s2;

The ‘+’ operator is not an optimized way of string concatenation as the string is a mutable object and each of these operations create immultiple objects.

Instead use a StringBuffer object that is mutable (can be changed) and re-write the code as:
String Buffer sBuff = new StringBuffer(“abc”);

Exception handling

Try/ catch blocks will be added in all methods where exceptions can be expected due to data operations within the method or other method involcations. The exceptions that are caught NullPointerException/ ArrayIndexOutOfBoundsException/ SQLException in the DAO/ Impl/ Proxy layers will be wrapped into the module-specific exception object and propagated downsteam i.e. towards the calling class. The exception object will be populated with the error code corresponding to the technical or business exception encountered.

Eg.            Method Call Sequence

Action -> Proxy -> Impl -> DAO
Exception Throwing sequence

DAO (catch exception and throws to) -> Impl (catch….)-> Proxy (catch..) -> Action

Based on the error code the Action class will decide on whether an error message needs to be displayed to the user and will map the error code to the corresponding error message.

No blank catch blocks should be present in the code. All the exceptions should be logged into the application log files via the eCI Logging statement and the printStackTrace() method of the Exception class.

Finally block

All methods should contain a finally block
This block should contain code to cleanup of variables used declared and used within the method.
No return statements should be defined inside the finally block of the methods.

Commented code blocks

There should be no commented code blocks in the java source files. This is often caused by copying code blocks from existing source files as a reference. As a part of this the comments from the source class also get copied over.

System.out.println ()

No System.out.println() statements should be present in the java source files. The statements that were added during the initial development phase have to now be replaced with the appropriate eCI Logging statements (Error/ Warning/ Debug/ Info). There should be no commented System.out.println() statements either.


Import of Classes

Import only the classes that are required from a package. Import the entire package only when a large number of classes from that package are going to be used.

Multiple decisions

In Java the switch - case statement can handle only chars, bytes and ints. Under this circumstance it may be required to write nested If statements. In this case when testing multiple decisions, check the most commonly occurring first. Restrict nested If’s to three levels by using the fall through logic.

Creation of Packages

It is advisable to create packages at the outset of coding classes. This ensures that a full testing of all classes is carried out using the packaging. If done at the end it can cause multiple problems.

Use of Static Class

A static class is equivalent to global declarations in other languages. Hence it must be used sparingly and with care. In the Browser environment, the static class gets loaded into memory on the first call to a  static method in the class. It resides in memory till the Browser is exited. This means that even if an applet which uses the static class is stopped, the static class is still alive. Hence when the applet restarts on coming back to the page containing the applet, it will get the static class with the last set of values.  The static class is useful in inter applet communication across Frames and to keep some application parameters in memory. But since it is resident in memory, if too many static classes are present it could affect the performance of the system or if multiple instances of the same applet exists it could result in overwriting the contents of the static class as in the case of any global variable.

Coding of URL’s

Very often when coding from an applet it may be required to get the URL of the document on which the applet is embedded or of the applet itself. Do not hard code these URL’s but rather use getCodeBase(), getDocumentBase, getHost() methods to retrieve the required URL.

Note : The above is applicable only to web based java applications that deal with request  objects .

Security Feature of Java

The following security features are recommended for applet implementations in Java.

Decisions about access to sensitive resources are made by the security manager, which is an instance of the SecurityManager class. Once a security manager has been set using System.setSecurityManager, it is always a security violation to try to set a new security manager. There can be only one security manager in an application.  The implementation of the SecurityManager class that is part of the core Java library is not very useful because it is an implementation that denies everything no matter what the source. To implement a security policy, the SecurityManager, must be subclassed, overriding the methods to determine resource access according to policies that are defined.  But override only methods that are required. By allowing access, there could be many subtle implications which must be investigated.  The security manager doesn’t have all the information that it needs to do a good job of resource tracking. For instance when the checkAccess(Threadgroup) method is called, the security manager doesn’t know whether a thread is being created or an entire thread group is being destroyed.

Use of Threads

Java incorporates threads into its design.  But some of the points to take into consideration before using threads.
·         The memory requirements of a thread include the memory for its Thread object and perhaps runnable object.
·         On a low level, a thread has memory for its execution stack associated with it.
·         A thread may require kernel resources from the underlying operating system
·         The more threads, the more the system has to manage
·         An application can be paralleled only by the number of available processors

A thread is a resource that should be used carefully. Not only can the use of threads increase the resource requirements of an application, they can also decrease its performance. An application that can be split among very independent threads is much easier to create than one where the threads require much interaction between them. The more threads there are that need to cooperate with one another, the more chances there are for subtle errors and performance problems. It may very well turn out that a multithreaded application will be spending much of its time synchronizing rather than doing work. In that case, it makes better sense to decrease the threads or do the entire application in a single thread.

Error Messages

·        Error Message should be raised properly wherever necessary.

·        Error messages used should be clear and consistent

·           Error messages should not blame the user and should not be technical. The technical errors      can be logged into a specific location.

·        Exceptions should be handled specifically rather than generally.

                         Catch (NumberFormatException e)

            Instead of just
            Catch (Exception e)

·           Error/Information messages must be stored in a property file and then accessed to display   whenever necessary.

·        It is recommended to have a logging utility to log all the errors in a common place (eg: database    table or a file in the SilverStream server) which will be helpful in case of any exceptions.

·        Use exception.getmessage () while logging exceptions, instead of hardcoding your own log  messages.

  Session Objects

·         Session object should be created at only one place in the application.

·         For the Session Bean implement the SessionBean interface in a SessionAdapter class and extend the SessionAdapter class in the SessionBean.  So that in every session bean all the methods of SessionBean interface need not be implemented.

Performance related

·           Re-usable objects are to be created as static objects in code, in order to avoid instantiating it multiple times, which will have an impact on performance.

For e.g. the logger object could be created once at the server level and the same object could be re-used.

·            File read operations must be restricted to a minimum. Instead of reading different parameters    from the same parameter file again and again, it is better to load the entire property file into memory once and read its contents from the memory thereafter.

·            Stringbuffers to be used instead of Strings when large string values are assigned to the      variables.

·            Objects should be reused after a clean up instead of reinstantiation.

·            If possible declare the classes as final.

·            Synchronize should never be used on private methods since private methods are generally invoked by public methods resulting in unnecessary overhead.

·            Use ArrayList instead of Vector and HashMap/TreeMap instead of Hastable. ArrayList and HashMaps don’t have synchronized methods like their counterparts Vector and Hashtable, thereby enhancing performance.


Popular posts from this blog

ORACLE 9i practice solutions

Created by BCL easyConverter SDK 3 (HTML Version)

Hackerrank > SQL > Basic Select

01-Select All
Given a City table, whose fields are described as +-------------+----------+ | Field       | Type     | +-------------+----------+ | ID          | int(11)  | | Name        | char(35) | | CountryCode | char(3)  | | District    | char(20) | | Population  | int(11)  | +-------------+----------+
write a query that will fetch all columns for every row in the table.

My Solution
02-Select by ID
Given a City table, whose fields are described as

Zoho Puzzle Questions With Answers

Measuring Time Logic Puzzle You are given with two ropes with variable width. However if we start burning both the ropes, they will burn at exactly same time i.e. an hour. The ropes are non-homogeneous in nature. You are asked to measure 45 minutes by using these two ropes.

How can you do it?

Please note that you can’t break the rope in half as it is being clearly stated that the ropes are non-homogeneous in nature.
Answer & Explanation Solution: 45 minutes

Explanation :
All you have to do is burn the first rope from both the ends and the second rope from one end only simultaneously. The first rope will burn in 30 minutes (half of an hour since we burned from both sides) while the other rope would have burnt half. At this moment, light the second rope from the other end as well. Where, the second rope would have taken half an hour more to burn completely, it will take just 15 minutes as we have lit it from the other end too.

Thus you have successfully calculated 30+15 = 45 minutes …